def before_request(self): current_app.logger.debug("Restricting access: %s" % str(current_user.is_authenticated())) if not current_user.is_authenticated(): return redirect(url_for("user.login", next=request.url)) elif not current_user.has_roles("admin"): current_app.logger.debug("%s, %s" % (current_user.has_roles("admin"), str(current_user.roles))) return abort(403)
def edit_menu_page(id=None, name=None): menuItems = getMenuItems(id, name) isOwner = current_user.has_roles('owner') isWaiter = current_user.has_roles('waiter') return render_template('menu/menu_page.html', title="Edit Menu", menuItems=menuItems, editable=True, isOwner=isOwner, isWaiter=isWaiter)
def collection(collection_name): """ Fetch collection from Collection table """ collection = Collection.query.filter_by(name=collection_name).first() if collection is None: abort(404) user = User.query.filter_by(id=collection.user_id).first() # only admin and owner can view if user != current_user and not current_user.has_roles('admin'): abort(404) template = "contribute/collection.html" if current_user.has_roles('admin'): template = "admin/collection.html" raw_files = dict() processed_files = dict() user_dir = "uploads/{}".format(collection.user_id) raw_dataset = user_dir + '/' + str(collection_name) if os.path.isdir(raw_dataset): for file in glob.glob("{}/*".format(raw_dataset)): fname = file.split(os.sep)[-1] modified_time = time.ctime(os.path.getmtime(file)) if fname in raw_files: raw_files[fname].append(modified_time) else: raw_files[fname] = modified_time collection_dir = PROCESSED_IMAGE_DIR + '/' + str(collection_name) if not os.path.isdir(collection_dir): return render_template( template, collection=collection, files=raw_files, processed_files=processed_files, user=user) modified_time = time.ctime(os.path.getmtime(collection_dir)) processed_files[collection_name] = modified_time return render_template( template, collection=collection, files=raw_files, processed_files=processed_files, user=user)
def update_assignment_categories_json(class_id, ids_string): if owns_class(class_id) or current_user.has_roles('admin'): # for really large bulk edits, a more efficient solution should be used # create list of strings containing all ids being updated id_list = ids_string.split(",") data = request.get_json() for id_ in id_list: assignment_category = db.session.query(AssignmentCategory).filter( AssignmentCategory.id == id_).one_or_none() for key, value in data[id_].items(): if key == "weight": if "%" in value: value = value.strip('%') if safe_add_to_total_weight(value, class_id): setattr(assignment_category, key, value) else: db.session.rollback() return render_template('json/too_much_weight.json') else: setattr(assignment_category, key, value) db.session.commit() # convert string list to integers for filtering id_list = list(map(int, id_list)) object_list = db.session.query(AssignmentCategory).filter(AssignmentCategory.id.in_(id_list)).all() extra = cat_class_avg(object_list) return render_template('json/data.json', objects=object_list, column_list=AssignmentCategory.__mapper__.c.keys(), extra_name="class_avg", extra=extra) else: return redirect(url_for('auth.login'))
def search_results(search): results = [] search_string = search.search.data if search_string: import re search_string_list = re.sub("[^\W]", " ", search_string).split() qry = db.session.query(Book).filter(Book.title == search_string) results = qry.all() else: qry = db.session.query(Book) results = qry.all() if not results: flash(lazy_gettext(u'No results found!'), 'info') return redirect(url_for('search')) else: # display results table = BookResults(results) if current_user.has_roles('Admin'): table.add_column( 'edit', LinkCol(lazy_gettext(u'Edit'), '.edit', url_kwargs=dict(id='id'))) table.border = True return render_template('books/results.html', table=table, form=search)
def view_profile(id): if current_user.has_roles('Admin') and id == current_user.id: user_tournaments = db.session.query(Tournament).join( User.tournaments).filter(User.id == id).all() return render_template('admin/profile.html', user_tournaments=user_tournaments) else: user_tournaments = db.session.query(Tournament).join( User.tournaments).join( UsersTournaments, UsersTournaments.user_id == User.id).with_entities( Tournament.id, Tournament.name, Tournament.start_date, Tournament.end_date, Tournament.players_admited, Tournament.elo_limit_low, Tournament.elo_limit_high, UsersTournaments.result).filter(User.id == id).order_by( Tournament.start_date).all() user_data = db.session.query(User).filter(User.id == id).first() with urlopen( f"https://aoe2.net/api/leaderboard?game=aoe2de&leaderboard_id=3&start=1&count=1&steam_id={user_data.steam_id}" ) as response: source = response.read() data_1 = json.loads(source) with urlopen( f"https://aoe2.net/api/player/matches?game=aoe2de&count=5&steam_id={user_data.steam_id}" ) as response: source = response.read() data_2 = json.loads(source) return render_template('participant/profile.html', user_tournaments=user_tournaments, user_data=user_data, aoe_data=data_1['leaderboard'], matches_data=data_2)
def donate(campaign_id): if current_user.has_roles('admin'): m = re.search('(\d+)', campaign_id) id = m.group(0) return redirect("/admin/donate/"+str(id)) else: campaign = campaign_from_url(campaign_id) admin_fields_enable = False if request.method == 'GET': if (campaign.status != 'Approved'): return render_template('donor_form_not_open.html') elif (campaign.needs() <= 0): return render_template('donor_form_full.html') else: form = DonorForm() if current_user.is_active(): form.set_data(current_user) return render_template('donor_form.html', form=form, campaign=campaign, admin_fields_enable=admin_fields_enable) elif request.method == 'POST': form = DonorForm(request.form) if form.validate(): result = donate_service.create_donation(form, campaign) if not result['error']: return donate_service.ccavRequest(form, result['donation']) else: print result flash('Oops something went wrong, please try again') app.logger.warning(form.errors) return render_template('donor_form.html', form=form, campaign=campaign, admin_fields_enable=admin_fields_enable)
def _setup_sno_fields(self): sno_validator = self.prod_order_sno.sno.validators[0] sno_validator.series = 'PROD' sno_validator.new = True if not current_user.has_roles(tuple(self.admin_roles)): read_only(self.prod_order_sno.sno_generate) read_only(self.prod_order_sno.sno)
def search_results(search_string=None): results = [] search = BookSearchForm() if search.validate_on_submit(): return redirect(url_for('.search_results', search_string=search.search.data)) if search_string: search_string_list = search_string.split(' ') qry=Book.query.filter(Book.title.contains(search_string)) for string in search_string_list: subquery = Book.query.filter(or_(Book.title.contains(string), Book.author.contains(string), Book.publisher.contains(string), Book.isbn13.contains(string), Book.category.contains(string))) qry = qry.union(subquery) results = qry.all() else: results = Book.query.all() if not results: message = gettext(u'No results found!') flash(message,'info') return redirect(url_for('.search')) else: # display results table = BookResults(results) search.search.data = search_string if current_user.has_roles('Admin'): table.add_column('edit', LinkCol(_l(u'Edit'),'.edit',url_kwargs=dict(id='id'))) table.border = True return render_template('books/results.html', table=table, form=search)
def create_assignment_categories_json(class_id): if owns_class(class_id) or current_user.has_roles('admin'): data = request.get_json() new_row = AssignmentCategory() for key, value in data["0"].items(): if value == '': value = None if key == "weight": if "%" in value: value = value.strip('%') if safe_add_to_total_weight(value, class_id): setattr(new_row, key, value) else: db.session.rollback() return render_template('json/error_message/too_much_weight.json') else: setattr(new_row, key, value) setattr(new_row, "class_id", class_id) db.session.add(new_row) db.session.commit() object_list = list() object_list.append(new_row) extra = dict() extra[new_row.id] = "0%" return render_template('json/data.json', objects=object_list, column_list=AssignmentCategory.__mapper__.c.keys(), extra_name="class_avg", extra=extra) else: return redirect(url_for('auth.login'))
def get_assignment_categories_json(class_id): if owns_class(class_id) or current_user.has_roles('admin'): object_list = db.session.query(AssignmentCategory).filter(AssignmentCategory.class_id == class_id).all() extra = cat_class_avg(object_list) return render_template('json/data.json', objects=object_list, column_list=AssignmentCategory.__mapper__.c.keys(), extra_name="class_avg", extra=extra) else: return redirect(url_for('auth.login'))
def teacher(teacher_id): # returns teacher info if current_user.is_authenticated: if db.session.query(Teacher).with_entities(Teacher.userID).filter(Teacher.id == teacher_id).\ one_or_none() == current_user or\ current_user.has_roles('admin'): return jsonify(db.session.query(Teacher).filter(Teacher.id == teacher_id).one_or_none().serialize()) return url_for('auth.login')
def all_classes(): if current_user.is_authenticated: if current_user.has_roles('admin'): allclasses = list() for i in db.session.query(Class).all(): allclasses.append(i.serialize()) return jsonify(allclasses) return redirect(url_for('auth.login'))
def user_auth_check(form, field): fuser = field.data if current_user.has_roles(tuple(form.admin_roles)): full_names = [x.full_name for x in get_users_list()] if fuser in full_names: return else: raise ValidationError("User '{0}' not recognized.".format(fuser)) if fuser == current_user.full_name: if len(form.auth_roles): if current_user.has_roles(tuple(form.auth_roles)): return else: raise ValidationError("You are not authorized for this " "action.".format(fuser)) raise ValidationError("You are not authorized to act on behalf on {0} for" "this action".format(fuser))
def _setup_sno_fields(self): sno_validator = self.indent_sno.sno.validators[0] sno_validator.series = 'IDT' sno_validator.new = True if self.is_supplementary: sno_validator.parent = self.parent_indent_sno_str if not current_user.has_roles(tuple(self.admin_roles)): read_only(self.indent_sno.sno_generate) read_only(self.indent_sno.sno)
def get_assignments_json(class_id): if owns_class(class_id) or current_user.has_roles('admin'): object_list = db.session.query(Assignment).filter(Assignment.class_id == class_id).all() return render_template('json/data_dropdown.json', objects=object_list, object_type=assignment_obj_type, column_list=Assignment.__mapper__.c.keys(), pick_dict=assignment_cat_pick(class_id), pick_what=pick_what, send_pick_list=True) else: return redirect(url_for('auth.login'))
def menu_item_manager(): menuItems = getItems() isOwner = current_user.has_roles('owner') return render_template('menuitem/menu_page.html', purpose="Menu Item Managment", title="Item Managment", menuItems=menuItems, editable=True, isOwner=isOwner)
def uploads_signatures(filename): query = Submission.get_submission_by_signature(signature_filename=filename) # if elevated user or submission owner or major professor if current_user.has_roles(['admin', 'viewer', 'reviewer', 'helper']) or \ current_user.id == query.user_id or \ current_user.net_id == query.professor: return send_from_directory(current_app.config['SIGNATURE_FOLDER'], query.signature_file) else: return redirect(url_for('main.index'))
def teachers(): # list of teachers if current_user.is_authenticated: if current_user.has_roles('admin'): teacher_list = list() for t in db.session.query(Teacher).all(): teacher_list.append(t.serialize()) return jsonify(teacher_list) return url_for('auth.login')
def index(): results = Book.query.all() table = BookResults(results, no_items=lazy_gettext(u'No books in the database')) if current_user.has_roles('Admin'): table.add_column( 'edit', LinkCol(lazy_gettext(u'Edit'), '.edit', url_kwargs=dict(id='id'))) print(table) return render_template('books/index.html', table=table)
def profile(): # List all user info if current_user.has_roles('teacher'): teacher = db.session.query(Teacher).filter( Teacher.user_id == current_user.id).one_or_none() return render_template('teacher/profile.html', teacher=teacher) else: return render_template_string( "<h1>Profile not available, please contact [email protected]</h1>" )
def uploads_submissions(filename): query = Revision.get_revision_by_filename(filename=filename) submission = Submission.get_submission_by_id(submission_id=query.submission_id) # if elevated user or submission owner or major professor if current_user.has_roles(['admin', 'viewer', 'reviewer', 'helper']) or \ current_user.id == submission.user_id or \ current_user.net_id == submission.professor: return send_from_directory(current_app.config['SUBMISSION_FOLDER'], query.file) else: return redirect(url_for('main.index'))
def delete_assignments_json(class_id, ids_string): if owns_class(class_id) or current_user.has_roles('admin'): # create list of strings containing all ids being deleted and then convert to integers for filtering id_list = ids_string.split(",") id_list = list(map(int, id_list)) db.session.query(Assignment).filter(Assignment.id.in_(id_list)).delete(synchronize_session=False) db.session.commit() return render_template_string("{}") else: return redirect(url_for('auth.login'))
def member_page(): if current_user.has_roles('Admin'): users = User.query.all() users_array = [] for user in users: detail = UserDetail.query.filter_by(user_id=user.id).first() if detail!=None: users_array.append([user.id, user.email, detail.name, detail.mentor_or_mentee, detail.date_of_birth,detail.country_of_residence, detail.city_of_residence]) return render_template('./admin/members.html', users=users_array) return redirect('/account')
def remove_media(md5): if current_user.has_roles('admin'): if md5.startswith('anon'): media = Media.query.filter_by(uploader=md5, hidden=False).all() else: media = Media.query.filter_by(md5=md5).all() for one in media: reports = Report.query.filter_by(media_md5=one.md5).all() for report in reports: report.status = 'removed' db.session.add(report) if 'Underage' in report.reason or 'Dox (Reveal of personal information)' in report.reason: user = User.query.filter_by( username=reports[0].reported_by).first() if user: modify_credit_balance( user, 100, 'Received 100 Credits for successfull reporting an illegal image' ) delete_media(one.filename, one.thumbnail) one.hidden = True db.session.add(one) db.session.commit() flash(f"{len(media)} Images Removed") else: if current_user.has_roles('free_delete'): media = Media.query.filter_by(md5=md5).first_or_404() media.hidden = True db.session.add(media) elif current_user.credits - 1000 >= 0: media = Media.query.filter_by(md5=md5).first_or_404() #delete_media(media.filename,media.thumbnail) media.hidden = True db.session.add(media) modify_credit_balance(current_user, -1000, f'Removed image {md5}') db.session.add(current_user) else: flash('Not enough credits to remove image') db.session.commit() return redirect(url_for('reported_media'))
def user_home(): # direct to correct profile page or admin overview if current_user.has_roles('admin'): render_template_string("<h1>Admin view under construction</h1>") elif current_user.has_roles('teacher'): teacher_id = db.session.query(Teacher).with_entities( Teacher.id).filter( Teacher.user_id == current_user.id).one_or_none() class_ids = db.session.query(teachers_classes).with_entities( teachers_classes.c.class_id).filter( teachers_classes.c.teacher_id == teacher_id).all() class_list = db.session.query(Class).filter( and_(Class.id.in_(class_ids), Class.in_session == True)).all() old_classes = db.session.query(Class).filter( and_(Class.id.in_(class_ids), Class.in_session == False)).all() return render_template('teacher/overview.html', class_list=class_list, old_classes=old_classes) else: return render_template_string( "<h1>Site Administrator has not assigned you a role, please contact [email protected]</h1>" )
def teacher_classes(teacher_id): # returns a teachers classes if current_user.is_authenticated: if db.session.query(teachers_classes).with_entities(teachers_classes.c.TeacherID).\ filter(teachers_classes.c.ClassID == teacher_id).one_or_none() == db.session.query(Teacher).\ with_entities(Teacher.id).filter(Teacher.userID == current_user.id).one_or_none() or\ current_user.has_roles('admin'): class_list = list() for classes in db.session.query(teachers_classes).with_entities(teachers_classes.c.ClassID).\ filter(teachers_classes.c.TeacherID == teacher_id).all(): class_list.append(db.session.query(Class).with_entities(Class.id, Class.name).filter(Class.id == classes).one_or_none()) return jsonify(class_list) return url_for('auth.login')
def get_download(md5): if current_user.has_roles('free_download'): media = Media.query.filter_by(md5=md5, hidden=False).first_or_404() return redirect(f"{app.config['CDN_URL']}{media.filename}") elif current_user.credits - 100 >= 0: modify_credit_balance(current_user, -100, 'Paid 100 Credits for downloading an image') media = Media.query.filter_by(md5=md5, hidden=False).first_or_404() return redirect(f"{app.config['CDN_URL']}{media.filename}") else: flash( 'You do not have enough credits to download this file. 100 Credits required' ) return redirect(url_for('show_media', md5=md5))
def mynavbar(): if current_user.is_anonymous: navbar = Navbar('', View(gettext(u'Login'), 'user.login')) elif current_user.has_roles('Admin'): navbar = Navbar( '', View(gettext(u'Home'), 'books.index'), Subgroup( gettext(u'Books'), View(gettext(u'New Book'), 'books.new_book'), View(gettext(u'List'), 'books.index'), View(gettext(u'Search'), 'books.search'), ), Subgroup( current_user.username, View(gettext(u'Add user'), 'auth.register'), View(gettext(u'User list'), 'auth.userlist'), View(gettext(u'Show Barcde'), 'auth.barcode', userid=current_user.id), View(gettext(u'Edit password'), 'auth.edit', userid=current_user.id), Separator(), View(gettext(u'Logout'), 'user.logout'), ), ) else: navbar = Navbar( '', View(gettext(u'Home'), 'books.index'), Subgroup( gettext(u'Books'), View(gettext(u'List'), 'books.index'), View(gettext(u'Search'), 'books.search'), ), Subgroup( current_user.username, View(gettext(u'Show Barcde'), 'auth.barcode', userid=current_user.id), View(gettext(u'Edit password'), 'auth.edit', userid=current_user.id), Separator(), View(gettext(u'Logout'), 'user.logout'), ), ) return navbar
def edit(userid): qry = db.session.query(User).filter(User.id==userid) user = qry.first() if user: if user.username == current_user.username: form = UserSelfEditForm() if form.validate_on_submit(): # Save modifications if form.new_password.data is not '' and check_password_hash(user.password, form.old_password.data): user.password = generate_password_hash(form.new_password.data) elif form.new_password.data is not '': flash(lazy_gettext(u'Incorrect old password')) user.locale = form.language.data print(current_user.locale)# = form.language.data db.session.commit() babrefresh() flash(lazy_gettext(u'User \"{}\" updated successfully!').format(user.username)) return redirect(url_for('books.index')) return render_template('auth/edit.html', form=form, username=user.username) elif current_user.has_roles('Admin'): form = UserEditForm() if form.validate_on_submit(): # Save modifications user.password = generate_password_hash(form.password.data) user.admin = form.admin.data db.session.commit() flash(lazy_gettext(u'User updated successfully!')) return redirect(url_for('.userlist')) return render_template('auth/edit.html', form=form, username=user.username) else: flash(lazy_gettext(u"You don't have the rights to edit user: \"{username}\"").format(username=userid.hex)) redirect(url_for('.userlist')) else: flash(lazy_gettext(u'ERROR: User \"{username}\" doesn''t exist').format(username=userid.hex)) return redirect(url_for('.userlist'))
def reported_media(): page = request.args.get('page', 1, type=int) if current_user.has_roles('admin'): media = Report.query.filter_by(status='new').order_by( Report.date.desc()).paginate(page, app.config['POSTS_PER_PAGE'], True) response = make_response( render_template('user_reports.html', media=media)) else: media = Report.query.filter_by( reported_by=current_user.username).order_by( Report.date.desc()).paginate(page, app.config['POSTS_PER_PAGE'], True) response = make_response( render_template('user_reports.html', media=media)) return response
def donate(campaign_id): if current_user.has_roles('admin'): return redirect("/admin/donate/"+str(campaign_id)) else: campaign = Campaign.query.get(campaign_id) admin_fields_enable = False if request.method == 'GET': form = DonorForm() if current_user.is_active(): form.set_data(current_user) return render_template('donor_form.html', form=form, campaign=campaign, admin_fields_enable=admin_fields_enable) elif request.method == 'POST': form = DonorForm(request.form) if form.validate(): result = donate_service.create_donation(form, campaign) if not result['error']: return donate_service.ccavRequest(form, result['donation']) else: print result flash('Oops something went wrong, please try again') app.logger.warning(form.errors) return render_template('donor_form.html', form=form, campaign=campaign, admin_fields_enable=admin_fields_enable)
def restrict_access(): if not current_user.is_authenticated(): return redirect(url_for("user.login", next=request.url)) elif not current_user.has_roles("admin"): return abort(403)
def user_has_roles(required_roles): return logged_in() and current_user.has_roles(required_roles)
def _setup_secure_fields(self): if not self.user.data: self.user.data = current_user.full_name if not current_user.has_roles(tuple(self.admin_roles)): read_only(self.user) read_only(self.rdate)
def campaign(id): campaign = campaign_from_url(id) if request.method == 'GET' or request.method == 'HEAD': return render_template('campaign.html', campaign=campaign, enable_inactive_campaign=current_user.is_active() and current_user.has_roles('admin')) else: form = BeneficiarySignupForm(request.form) if form.validate(): image = request.files['imageUpload'] filename = secure_filename(image.filename) if filename and allowed_file(filename): full_save_path = os.path.join(app.config['UPLOAD_DIRECTORY'], 'tmp', filename) image.save(full_save_path) result = signup_service.edit_beneficiary(campaign, form, filename) if not result['error']: flash('You successfully edited the campaign') return render_template('campaign.html', campaign=campaign, enable_inactive_campaign=current_user.is_active() and current_user.has_roles('admin')) else: flash('Oops something went wrong, please try again') return render_template('beneficiary_form.html', form=form)