def validate_edit_project(project, *roles): """ Validate that the logged-in user is privileged to edit a particular project :param project: Project model instance :return: True/False """ # if project owner is currently logged-in user, all is ok if project.owner_id == current_user.id: return True # admin and root users can always edit everything if current_user.has_role('admin') or current_user.has_role('root'): return True # if the currently logged-in user has any of the specified roles, allow edit for role in roles: if current_user.has_role(role): return True # if the current user is a convenor for any of the pclasses to which we're attached, allow edit if any([ item.is_convenor(current_user.id) for item in project.project_classes ]): return True flash( 'This project belongs to another user. To edit it, you must be a suitable convenor or an administrator.' ) return False
def is_accessible(self): if current_user.is_authenticated \ and current_user.has_role('admin') \ or current_user.has_role('super'): return True else: return False
def set_scope(sender, item): if current_user.has_role('network-admin') or current_user.has_role( 'gateway-admin'): item.network_id = current_user.network_id if current_user.has_role('gateway-admin'): item.gateway_id = current_user.gateway_id
def dashboard(): if current_user.has_role('primeserver'): form = UpdateAccountPrimeServerForm() else: form = UpdateAccountForm() if form.validate_on_submit(): if form.picture.data: picture_file = save_picture(form.picture.data) current_user.image_file = picture_file current_user.username = form.username.data current_user.email = form.email.data.lower() current_user.bio = form.bio.data current_user.favsong = form.favsong.data if current_user.has_role('primeserver'): current_user.ign = form.ign.data current_user.noteskin = form.noteskin.data current_user.scrollspeed = round(0.5 * round(float(form.scrollspeed.data) / 0.5), 1) current_user.modifiers = current_user.modifiers | mods_to_int([], form.judgement.data) current_user.psupdate = "True" if not form.psupdate.data else "False" db.session.commit() flash('Account details updated!', 'success') return redirect(url_for('users.dashboard')) elif request.method == "GET": form.username.data = current_user.username form.email.data = current_user.email form.bio.data = current_user.bio form.favsong.data = current_user.favsong if current_user.has_role('primeserver'): form.ign.data = current_user.ign form.noteskin.data = current_user.noteskin form.scrollspeed.data = current_user.scrollspeed form.judgement.data = int_to_judge(current_user.modifiers) form.psupdate.data = current_user.psupdate == "False" image_file = url_for('static', filename='profile_pics/' + current_user.image_file) return render_template("dashboard.html", title="Dashboard", image_file=image_file, form=form, current_user=current_user)
def profile(self): if request.args.get('id') and current_user.has_role('admin'): user = get_object_or_404(User, id=request.args.get('id')) else: user = current_user if request.method == "POST": for setting in request.form: if request.form[setting]: user.settings[setting] = request.form[setting] user.save() for setting in request.form: if not request.form[setting]: user.settings.pop(setting, None) user.save() if current_user.has_role('admin') and user.id != current_user.id: return render_template( "user/profile_admin.html", available_settings=User.get_available_settings(), user=user) else: return render_template( "user/profile.html", available_settings=User.get_available_settings(), user=user)
def profile(): """ Home page for the employee. GET request : displays all the appointments that can be, cannot be, or have been booked. Employees can view their calendar, managers the calendars of their location's employees POST request : changes the status of appointmnents from bookable to not bookable ('tbd') and vice versa. """ if request.method == 'POST': data_list = json.loads(request.form['submit_check_val']) toggle_appointments(data_list) return redirect(url_for('profile')) if request.method == 'GET': form = ChangePwdForm() if current_user.has_role('admin'): return redirect('/admin') if current_user.has_role('end-user'): data = query_user_appointment(current_user.id) return render_template('profile.html', user_record=data, form=form) if current_user.has_role('manager'): users = (User.query .filter_by(branch_id=current_user.branch_id) .join(User.roles) .filter(Role.id == 2) .all()) data=[query_user_appointment(user.id) for user in users] return render_template("manager_profile.html", data=data, form=form)
def part_prj(): params={} sql="""select pprojid,ptitle,up.ownerid,u.name,u.email,rawfolder,instrumtype,ep.title ,(select count(*) from part_samples where pprojid=up.pprojid) samplecount from part_projects up left JOIN projects ep on up.projid=ep.projid LEFT JOIN users u on ownerid=u.id """ sql += " where 1=1 " if not current_user.has_role(database.AdministratorLabel): sql+=" and ownerid=%d"%(current_user.id,) if gvg('filt_title','')!='': sql +=" and ( up.ptitle ilike '%%'||%(title)s ||'%%' or to_char(up.pprojid,'999999') like '%%'||%(title)s or ep.title ilike '%%'||%(title)s ||'%%' or to_char(ep.projid,'999999') like '%%'||%(title)s) " params['title']=gvg('filt_title') if gvg('filt_instrum','')!='': sql +=" and up.instrumtype ilike '%%'||%(filt_instrum)s ||'%%' " params['filt_instrum']=gvg('filt_instrum') sql+=" order by lower(ep.title),lower(ptitle)" res = GetAll(sql,params) #,debug=True # app.logger.info("res=%s",res) CanCreate=False if current_user.has_role(database.AdministratorLabel) or current_user.has_role(database.ProjectCreatorLabel): CanCreate=True g.headcenter = "<h4>Particle Projects management</h4><a href='/part/'>Particle Module Home</a>" return PrintInCharte( render_template('part/list.html', PrjList=res, CanCreate=CanCreate, AppManagerMailto=appli.GetAppManagerMailto() , filt_title=gvg('filt_title'), filt_subset=gvg('filt_subset'), filt_instrum=gvg('filt_instrum')))
def find_supplier_draft_services(supplier_id): supplier = data_api_client.get_supplier(supplier_id)["suppliers"] frameworks = data_api_client.find_frameworks()['frameworks'] if current_user.has_role('admin-ccs-sourcing'): visible_framework_statuses = ["pending", "standstill", "live", "expired"] elif current_user.has_role('admin-framework-manager'): visible_framework_statuses = ["open", "pending", "standstill", "live", "expired"] else: # No other roles can access this page yet, but we might want to add them later visible_framework_statuses = [] frameworks = (fw for fw in frameworks if fw['status'] in visible_framework_statuses) frameworks_draft_services = { framework_slug: draft_services for framework_slug, draft_services in ( (framework_slug, _draft_services_annotated_unanswered_counts(framework_slug, draft_services),) for framework_slug, draft_services in groupby(sorted( data_api_client.find_draft_services_iter(supplier_id), key=lambda draft_service: (draft_service["frameworkSlug"], draft_service["createdAt"]), ), key=lambda draft_service: draft_service["frameworkSlug"]) ) if draft_services is not None # omit frameworks for which we couldn't retrieve the manifest } return render_template( 'view_supplier_draft_services.html', frameworks=frameworks, frameworks_draft_services=frameworks_draft_services, supplier=supplier, )
def ListTasks(owner=None): g.headcenter = "<H3>Task Monitor</h3>" AddTaskSummaryForTemplate() seeall = "" if current_user.has_role( database.AdministratorLabel) and gvg("seeall") == 'Y': tasks = Task.query.filter_by().order_by("id").all() seeall = '&seeall=Y' else: tasks = Task.query.filter_by( owner_id=current_user.id).order_by("id").all() txt = "" if gvg("cleandone") == 'Y' or gvg("cleanerror") == 'Y' or gvg( "cleanall") == 'Y': txt = "Cleanning process result :<br>" for t in tasks: if (gvg("cleandone")=='Y' and t.taskstate=='Done') or (gvg("cleanall")=='Y') \ or (gvg("cleanerror")=='Y' and t.taskstate=='Error') : txt += DoTaskClean(t.id) tasks = Task.query.filter_by( owner_id=current_user.id).order_by("id").all() # txt += "<a class='btn btn-default' href=?cleandone=Y>Clean All Done</a> <a class='btn btn-default' href=?cleanerror=Y>Clean All Error</a> <a class='btn btn-default' href=?cleanall=Y>Clean All (warning !!!)</a> Task count : "+str(len(tasks)) return render_template('task/listall.html', tasks=tasks, header=txt, len_tasks=len(tasks), seeall=seeall, IsAdmin=current_user.has_role( database.AdministratorLabel))
def user_edit(id): if not current_user.has_role(Role.ROLE_ADMIN) and current_user.id != id: abort(403) user = User.query.get_or_404(id) form = EditUserForm(user.email) if request.method == 'GET': form.full(user) if form.validate_on_submit(): user.email = form.email.data user.first_name = form.first_name.data user.middle_name = form.middle_name.data user.second_name = form.second_name.data user.send_flag = form.send_flag.data user.vector = form.vector.data if form.role.data != user.get_role( ).name and not current_user.has_role(Role.ROLE_SECRETARY): user.set_role(form.role.data) if form.avatar_image.data: file = form.avatar_image.data user.avatar = str(uuid.uuid4()) + os.path.splitext( file.filename)[1] path = os.path.join(current_app.config['STATIC_DIR'], current_app.config['UPLOAD_AVATAR_FOLDER']) file.save(os.path.join(path, user.avatar)) db.session.commit() form.full(user) flash('Пользователь изменен', current_app.config['SUCCESS_FLASH']) return render_template('users/user_edit.html', form=form)
def is_listable(record, message=False): """ Determine whether the currently logged-in user has permissions to view the documents attached to a SubmissionRecord :param record: :param message: :return: """ # 'root', 'admin', 'faculty' and 'office' users can always list the documents attached to a SubmissionRecord if current_user.has_role('root') or current_user.has_role('admin') or current_user.has_role('faculty') \ or current_user.has_role('office'): return True # 'student' users can only list the documents attached if they are the submitter if current_user.has_role('student'): if current_user.id == record.owner.student.id: return True if message: flash( 'It is only possible to view the documents attached to this submission record if you are the ' 'submitter.', 'info') return False if message: flash( 'You do not have sufficient privileges to view the documents attached to this submission record', 'info') return False
def change_password(): if current_user.has_role('admin') and request.args.get('id'): u = get_object_or_404(User, id=request.args.get('id')) else: u = current_user current = request.form.get("current", "") new = request.form.get("new", "") bis = request.form.get("bis", "") if not current_user.has_role('admin'): if not check_password_hash(u.password, current): flash('Current password is invalid', 'danger') return redirect(request.referrer) if new != bis: flash('Password confirmation differs from new password.', 'danger') else: u = set_password(u, new) u.save() # re-execute the login if the changes were made on current_user if u.id == current_user.id: login_user(u) flash('Password was successfully changed.', 'success') return redirect(request.referrer)
def validate_schedule_inspector(record): """ Validate that the logged-in user is entitled to view the schedule inspector for a given scheduling attempt :param record: :return: """ if current_user.has_role('root') or current_user.has_role('admin'): return True if current_user.has_role('faculty'): if record.published: for pclass in record.available_pclasses: if pclass.is_convenor(current_user.id): return True else: flash( 'The schedule owner has not yet made this match available to project convenors.', 'info') return False flash( 'This operation is available only to administrative users and project convenors.', 'error') return False
def delete(article_id): article = Article.query.get_or_404(article_id) if not (current_user.has_role('Administrator') or current_user.has_role( 'Editor')) and current_user.id != article.createdby: abort(403) article.delete() delete_image(article.image) return redirect(url_for('articles.list_view'))
def decorated_function(*args, **kwargs): if not current_user.is_authenticated: abort(403) if not (current_user.has_role("administrator") or current_user.has_role("writer")): abort(403) return f(*args, **kwargs)
def decorated_function(*args, **kwargs): if not current_user.is_authenticated: abort(403) if not ( current_user.has_role("administrator") or current_user.has_role("writer") ): abort(403) return f(*args, **kwargs)
def index(): if current_user.is_authenticated: if current_user.has_role("PICTURE_EDITOR"): return redirect(url_for("picture_editor_page")) elif current_user.has_role("LANGUAGE_CONSULTANT"): return redirect(url_for("language_consultant_page")) return redirect(url_for("mypage")) else: return redirect(url_for("auth_login"))
def app_state(): logged_in = current_user.is_authenticated if current_user else 0 is_admin = (current_user.has_role("administrator") if current_user and current_user.is_authenticated else 0) can_write_posts = ((current_user.has_role("administrator") or current_user.has_role("writer")) if current_user and current_user.is_authenticated else 0) username = (current_user.username if current_user and current_user.is_authenticated else "My Account") email = (current_user.email if current_user and current_user.is_authenticated else None) first_name = (current_user.first_name if current_user and current_user.is_authenticated else None) last_name = (current_user.last_name if current_user and current_user.is_authenticated else None) site_default = current_app.config["BLOG_DEFAULT_IMAGE"] image_widths = current_app.config["IMAGE_WIDTHS"].split(",") tiny_thumbnail_width = current_app.config["TINY_THUMBNAIL_WIDTH"] small_thumbnail_width = current_app.config["SMALL_THUMBNAIL_WIDTH"] large_thumbnail_width = current_app.config["LARGE_THUMBNAIL_WIDTH"] cloudinary_on = current_app.config["CLOUDINARY_ON"] cloudinary_account = current_app.config["CLOUDINARY_ACCOUNT"] settings = { "images": { "site_default": site_default, "widths": image_widths, "thumbnail_widths": { "tiny": tiny_thumbnail_width, "small": small_thumbnail_width, "large": large_thumbnail_width, }, "cloudinary": { "on": cloudinary_on, "account": cloudinary_account }, } } return dict( state={ "user": { "logged_in": logged_in, "is_admin": is_admin, "can_write_posts": can_write_posts, "account": { "username": username, "email": email, "first_name": first_name, "last_name": last_name, }, }, "settings": settings, })
def is_uploadable(record, message=False, allow_student=True, allow_faculty=True): """ Determine whether the currently logged-in user has permissions to upload a document to a SubmissionRecord :param allow_faculty: :param record: :param message: :param allow_student: :return: """ # 'root', 'admin', 'faculty' and 'office' users can always upload new documents to a SubmissionRecord if current_user.has_role('root') or current_user.has_role('admin') \ or current_user.has_role('office'): return True if current_user.has_role('faculty'): if allow_faculty: return True if message: flash( 'You do not have sufficient privileges to attach documents to this submission record. ' 'Please contact the convenor or an administrator to arrange for documents to be uploaded.', 'info') return False # 'student' users can only list the documents attached if they are the submitter if current_user.has_role('student'): if not allow_student: if message: flash( 'You do not have sufficient privileges to attach documents to this submission record.', 'info') return False if current_user.id == record.owner.student.id: return True if message: flash( 'It is only possible to attach documents to this submission record if you are the ' 'submitter.', 'info') return False if message: flash( 'You do not have sufficient privileges to attach documents to this submission record.', 'info') return False
def user_profile(): try: user_id = int(request.args.get('user_id')) except ValueError: flash("Invalid user_id parameter", 'danger') return render_template('result.html', heading="User profile unavailable") if current_user.id != user_id and not current_user.has_role('admin'): return _get_unauthorized_view() # leaving this trigger here because it's convenient if current_user.email in app.config.get('MAKE_ADMIN', []): if not current_user.has_role('admin'): admin = user_datastore.find_role('admin') user_datastore.add_role_to_user(current_user, admin) user_datastore.commit() flash("You have been upgraded to admin", 'success') this_user = user_datastore.find_user(id=user_id) if not this_user: flash("Unknown user_id", 'danger') return render_template('result.html', heading="User profile unavailable") form = get_form(EditUserForm) if request.method == 'POST': if form.validate(): this_user.first_name = form.first_name.data this_user.last_name = form.last_name.data this_user.nickname = form.nickname.data this_user.venmo_id = form.venmo_id.data user_datastore.commit() flash("Profile updated", 'success') return redirect(request.url) else: flash("Error in form validation", 'danger') return render_template('user_profile.html', this_user=this_user, edit_user=form, human_timestamp=mms.time_human_formatter, human_timediff=mms.time_diff_formatter, timestamp=mms.timestamp_formatter) # TODO make admins able to edit user page # pre-populate the form with the current values for attr in 'first_name,last_name,nickname,venmo_id'.split(','): setattr(getattr(form, attr), 'data', getattr(this_user, attr)) return render_template('user_profile.html', this_user=this_user, edit_user=form, human_timestamp=mms.time_human_formatter, human_timediff=mms.time_diff_formatter, timestamp=mms.timestamp_formatter)
def verify_submitter(sub: SubmittingStudent, message: bool = False): if sub.student_id != current_user.id \ and not current_user.has_role('admin') and not current_user.has_role('root'): if message: flash( 'You do not have permission to perform operations for this user. ' 'If you believe this is incorrect, contract the system administrator.', 'error') return False return True
def post(self): """Implement the POST.""" user = User.create(request.get_json()) editing_own_public_profile = str(current_user.id) == user.id and \ not ( current_user.has_role('system_librarian') and current_user.has_role('librarian') ) if editing_own_public_profile: Patron.set_communication_channel(user) return user.dumps()
def is_admin(current_user): if current_user.has_role('root') or current_user.has_role('admin'): return True if current_user.has_role('office'): return True if current_user.has_role('faculty'): return True return False
def decorated_view(*args, **kwargs): if len(roles) == 0: raise ValueError('Empty list used when requiring a role.') if not current_user.is_authenticated: return login_manager.unauthorized() if require_all and not all( current_user.has_role(role) for role in roles): return 'Forbidden', 403 elif not require_all and not any( current_user.has_role(role) for role in roles): return 'Forbidden', 403 return f(*args, **kwargs)
def decorated_view(*args, **kwargs): if len(roles) == 0: raise ValueError('Empty list used when requiring a role.') if not current_user.is_authenticated: raise werkzeug.exceptions.Forbidden() if require_all and not all( current_user.has_role(role) for role in roles): raise werkzeug.exceptions.Unauthorized() elif not require_all and not any( current_user.has_role(role) for role in roles): raise werkzeug.exceptions.Unauthorized() return f(*args, **kwargs)
def delete(self, id): char = PC.query.filter_by(id=id).one_or_none() if char is None: abort(404, "The requested character does not exist") if char.owner is not current_user.id: if current_user.has_role( "Player") and not current_user.has_role("GM"): abort(403, "You may only delete your own characters") db.session.delete(char) db.session.commit() return {"message": "Success"}
def journal_readonly(journal_id): if (not current_user.has_role("admin") or not current_user.has_role("editor") or not current_user.has_role("associate_editor")): abort(401) j = models.Journal.pull(journal_id) if j is None: abort(404) fc = formcontext.JournalFormFactory.get_form_context(role='readonly', source=j) return fc.render_template(edit_journal_page=True)
def journal_readonly(journal_id): if ( not current_user.has_role("admin") or not current_user.has_role("editor") or not current_user.has_role("associate_editor") ): abort(401) j = models.Journal.pull(journal_id) if j is None: abort(404) fc = formcontext.JournalFormFactory.get_form_context(role='readonly', source=j) return fc.render_template(edit_journal_page=True)
def edit(id): user = User.objects.get_or_404(id=id) if not (user.is_me() or current_user.has_role('editor')): abort(401, 'You cannot edit this profile.') if request.method == 'POST': fields = ['name', 'website', 'about'] for f in fields: setattr(user.profile, f, request.form.get(f)) user.profile.socials = {k.split('-')[1]: v for k, v in request.form.items() if k.startswith('socials-')} # Editor role if current_user.has_role('editor'): if request.form.get('editor'): current_app.user_datastore.add_role_to_user(user, 'editor') else: current_app.user_datastore.remove_role_from_user(user, 'editor') # Image upload image = request.files.get('image') if request.form.get('delete'): user.profile.delete_image() if image: maximum = current_app.config['USERS_IMAGE_MAX_CONTENT_LENGTH'] if file_exceeds(image, maximum): raise exceptions.RequestEntityTooLarge() if image.filename == '': message = ('There was an error in your profile submission: ' 'No selected file.') flash(message, 'error') return redirect(lang_url_for('users.edit', id=user.id)) if not allowed_file(image.filename): # TODO: https://github.com/cafebabel/cafebabel.com/issues/187 message = ('There was an error in your profile submission: ' 'Unallowed extension.') flash(message, 'error') return redirect(lang_url_for('users.edit', id=user.id)) user.profile.attach_image(image) user.save() flash('Your profile has been updated :-)') return redirect(user.detail_url) articles = Article.objects.filter(authors=user).hard_limit() translations = (Translation.objects(translators__in=[user]) .exclude('original_article')) return render_template( 'users/edit.html', user=user, is_full=False, articles=articles.select_related(max_depth=1), translations=translations.select_related(max_depth=1))
def is_editable(record: SubmissionRecord, period: SubmissionPeriodRecord = None, config: ProjectClassConfig = None, message: bool = False, asset: SubmittedAsset = None, allow_student: bool = True): # 'root', 'admin' and 'office' users can always edit SubmissionRecord data if current_user.has_role('root') or current_user.has_role( 'admin') or current_user.has_role('office'): return True if current_user.has_role('faculty'): # a SubmissionRecord is editable if the user is 'convenor' for the project class period = period or record.period config = config or period.config pclass = config.project_class if pclass.is_convenor(current_user.id): return True if message: flash( 'Only the project convenor can edit documents attached to this submission record', 'info') return False # below this point in the privilege hierarchy, editing is not possible if the period is already closed if period.closed: return False if current_user.has_role('student') and allow_student: # students can edit assets that they have uploaded, but not a SubmissionRecord as a whole if asset is not None and asset.uploaded_by is not None: if current_user.id == asset.uploaded_by.id: return True if message: flash( 'It is not possible to edit this document. You can only edit documents that you have ' 'uploaded yourself.', 'info') return False if message: flash( 'You do not have sufficient privileges to edit the documents attached to this submission record', 'info') return False
def add_item(): shows = {} if not current_user.has_role("admin") and not current_user.shows.all(): # TODO error handling return "add new show first" if current_user.has_role("admin"): result = requests.get(app.config["APP_BASE_URL"] + url_for("arcsi.list_shows")) shows = result.json() shows_sorted = sorted(shows, key=lambda k: k['name']) return render_template("item/add.html", shows=shows_sorted)
def validate_is_administrator(message=True): """ Ensure that user in an administrator :return: """ if not current_user.has_role('admin') and not current_user.has_role( 'root'): if message: flash('Only administrative users can perform this operation.', 'error') return False return True
def index(): """Return the talk list.""" event = g.current_event if not (event.talks_are_published or current_user.has_role('admin')): abort(404) return render_template('talks/index.html', talks=event.accepted_talks)
def application_update(id, step=None): old_application = data_api_client.get_application(id) if not can_user_view_application(old_application): abort(403, 'Not authorised to access application') if is_application_submitted(old_application) and not current_user.has_role('admin'): return redirect(url_for('.submit_application', id=id)) json = request.content_type == 'application/json' form_data = from_response(request) application = form_data['application'] if json else form_data try: del application['status'] except KeyError: pass result = data_api_client.update_application(id, application) if json: try: appdata = result['application'] del appdata['links'] except KeyError: pass return jsonify(result) else: return redirect(url_for('.render_application', id=id, step=form_data['next_step_slug']))
def get_info_from_file_number(file_number, privileged=False, filename=None): if current_user and current_user.is_authenticated and current_user.has_role('admin', 'developer', 'advocate', 'trainer'): privileged = True else: if has_request_context() and 'uid' in session: uid = session['uid'] else: uid = docassemble.base.functions.get_uid() #logmessage("get_info_from_file_number: privileged is " + str(privileged) + " and uid is " + str(uid)) result = dict() if privileged: upload = Uploads.query.filter_by(indexno=file_number).first() else: upload = Uploads.query.filter(and_(Uploads.indexno == file_number, or_(Uploads.key == uid, Uploads.private == False))).first() if upload: if filename is None: result['filename'] = upload.filename else: result['filename'] = filename result['extension'], result['mimetype'] = get_ext_and_mimetype(result['filename']) sf = SavedFile(file_number, extension=result['extension'], fix=True) result['path'] = sf.path result['fullpath'] = result['path'] + '.' + result['extension'] result['private'] = upload.private result['persistent'] = upload.persistent #logmessage("fullpath is " + str(result['fullpath'])) if 'path' not in result: logmessage("get_info_from_file_number: path is not in result for " + str(file_number)) return result final_filename = result['path'] + '.' + result['extension'] if os.path.isfile(final_filename): add_info_about_file(final_filename, result) # else: # logmessage("Filename " + final_filename + "did not exist.") return(result)
def decorated_view(*args, **kwargs): if not current_user.is_authenticated: abort(403) if not current_user.has_role(*role_names): abort(403) return func(*args, **kwargs)
def render_application(id, step=None, substep=None): application = data_api_client.get_application(id) if not can_user_view_application(application): abort(403, 'Not authorised to access application') if is_application_submitted(application) and not current_user.has_role('admin'): return redirect(url_for('.submit_application', id=id)) props = dict(application) props['basename'] = url_for('.render_application', id=id, step=None) props['form_options'] = { 'action': url_for('.render_application', id=id, step=step), 'submit_url': url_for('.submit_application', id=id), 'document_url': url_for('.upload_single_file', id=id, slug=''), 'authorise_url': url_for('.authorise_application', id=id), 'user_name': current_user.name, 'user_email': current_user.email_address } # Add service pricing if 'services' in application['application']: props['application']['domains'] = {'prices': {'maximum': {}}} for domain_name in application['application']['services'].keys(): props['application']['domains']['prices']['maximum'][domain_name] = ( application['domains']['prices']['maximum'][domain_name] ) widget = application['application'].get('type') == 'edit' and 'ProfileEdit' or 'ApplicantSignup' rendered_component = render_component('bundles/SellerRegistration/{}Widget.js'.format(widget), props) return render_template( '_react.html', component=rendered_component )
def order_detail(id): """订单查看""" order = Order.query.get_or_404(id) if not (order.chef_id == current_user.id or current_user.has_role('superuser')): flash(u'你没有权限查看这个订单', category='error') return abort(403) return render_template('chef/order_detail.html', order=order)
def meal_edit(id): """编辑meal""" meal = Meal.query.get_or_404(id) if not current_user.has_role('superuser') and not meal.chef_id == current_user.id: abort(403) form = MealEditForm() if form.validate_on_submit(): meal.name = form.name.data meal.description = form.description.data # update the begin and end date for meal_zipcode in meal.meal_zipcodes: meal_zipcode.begin_date = form.begin_date.data meal_zipcode.end_date = form.end_date.data zips = Zipcode.add_zips(form.zipcodes.data.split(',')) while (len(meal.meal_zipcodes) > 0): meal.meal_zipcodes.pop() print(meal.meal_zipcodes) # create new MealZipcode for zipcode in zips: meal_zipcode = MealZipcode(meal_id=meal.id, zipcode_id=zipcode.id, begin_date=form.begin_date.data, end_date=form.end_date.data) db.session.add(meal_zipcode) db.session.add(meal) db.session.commit() form.zipcodes.data = ','.join((zipcode.zipcode for zipcode in meal.zipcodes)) form.name.data = meal.name form.description.data = meal.description if len(meal.meal_zipcodes) > 0: form.begin_date.data = meal.meal_zipcodes[0].begin_date form.end_date.data = meal.meal_zipcodes[0].end_date return render_template('chef/meal_create.html', form=form)
def inner(*args, **kwargs): # a user needs at least one of the roles to be granted access for r in iterify(roles[0]): if current_user.has_role(r): return f(*args, **kwargs) else: abort(401)
def f(*args, **kwargs): """dummy wrapped function""" if current_user.has_role(role): return wrapped(*args, **kwargs) else: flash("You do not have the {role} role".format(role="role"), "warning") abort(403)
def restrict_to_role(role): if current_user.is_anonymous: flash('You are trying to access a protected area. Please log in first.', 'error') return redirect(url_for('account.login', next=request.url)) if not current_user.has_role(role): flash('You do not have permission to access this area of the site.', 'error') return redirect(url_for('doaj.home'))
def decorated_function(*args, **kwargs): if not current_user.is_authenticated: abort(403) if not current_user.has_role(role): abort(403) return f(*args, **kwargs)
def schedule(): event = g.current_event if not (event.schedule_is_published or current_user.has_role('admin')): abort(404) days = Day.query.filter(Day.event == event).order_by(Day.date) return render_template('talks/schedule.html', schedule=days)
def upload_single_file(id, slug): application = data_api_client.get_application(id) if not can_user_view_application(application): abort(403, 'Not authorised to access application') if is_application_submitted(application) and not current_user.has_role('admin'): abort(400, 'Application already submitted') return s3_upload_file_from_request(request, slug, os.path.join(S3_PATH, str(id)))
def decorated_view ( *args, **kw ): from flask_login import current_user, logout_user from flask import flash, redirect if current_user.is_authenticated() and current_user.has_role( role): return fn (*args, **kw) else: flash( "You do not have necessary permissions.", "error") return redirect ( "/")
def check_role(*args, **kwargs): """Perform the check.""" if current_user.is_anonymous: abort(401) if current_user.has_role(None, role) is False: abort(401) return handler_method(*args, **kwargs)
def download_single_file(id, slug): application = data_api_client.get_application(id) if not can_user_view_application(application) and not current_user.has_role('admin'): abort(403, 'Not authorised to access application') file = s3_download_file(slug, os.path.join(S3_PATH, str(id))) mimetype = mimetypes.guess_type(slug)[0] or 'binary/octet-stream' return Response(file, mimetype=mimetype)
def patch(self, id): if not request.json: abort(400) try: data = self.clear_update_data(request.json) except ValueError as e: db.session.rollback() return jsonify(error="Invalid data", error_details=str(e)) deserializer = self.SCHEMA.create_update_serializer() data['id'] = int(id) try: version_id = int(data.pop('version_id')) except (KeyError,ValueError): db.session.rollback() return jsonify(error="Version_id missing", error_details="") existing = self.model.query.filter(self.model.id == data['id']).with_for_update(of=self.model).one() if not existing: db.session.rollback() return jsonify(error="Unknown record", error_details="Id %d is not in table" % data['id']) if self.user_can_change: can_change_object(existing) else: if not current_user.has_role('superuser'): abort(403, 'Access denied') obj, errors = deserializer.load(data) if errors: db.session.rollback() return jsonify(error="Invalid data", error_details=errors) assert(existing.id == obj.id) can_change_object(obj) if version_id != obj.version_id: db.session.rollback() return jsonify(error="Stalled record", error_details="Your version %d, db version %d" % (version_id, obj.version_id)) obj.modified_by = current_user self.modify_update_object(obj) try: db.session.commit() except Exception as e: db.session.rollback() return jsonify(error="Database error", error_details=str(e)) return jsonify(id=obj.id, success=True)
def before_request(): if not current_user.is_authenticated: return redirect(url_for('auth.login')) if not current_user.has_role('chef') and \ request.endpoint != 'chef.chef_apply' and \ request.endpoint != 'chef.chef_apply_status': chefApply = ChefApply.query.filter_by(applicant_id=current_user.id) \ .first() if chefApply: return redirect(url_for('chef.chef_apply_status', id=chefApply.id)) return redirect(url_for('chef.chef_apply'))
def delete(self, id): entity = self.model.query.get_or_404(id) if self.user_can_change: can_delete_object(entity) else: if not current_user.has_role('superuser'): abort(403, 'Access denied') self.before_delete(entity) db.session.delete(entity) db.session.commit() return jsonify(id=id, success=True)
def editable(self): if not current_user.is_authenticated: return False else: return ( True if ( current_user.has_role("administrator") or self.user_id == current_user.id ) else False )
def order_edit(id): """处理,已发货、未发货""" order = Order.query.get_or_404(id) if not (order.chef_id == current_user.id or current_user.has_role('superuser')): flash(u'你没有权限查看这个订单', category='error') return abort(403) form = ChefOrderEditForm() if form.validate_on_submit(): order.status = form.status.data order.remark = form.remark.data form.status.data = order.status form.remark.data = order.remark return render_template('chef/order_edit.html', order=order, form=form)
def unlock(object_type, object_id): # first figure out if we are allowed to even contemplate this action if object_type not in ["journal", "suggestion"]: abort(404) if object_type == "journal": if not current_user.has_role("edit_journal"): abort(401) if object_type == "suggestion": if not current_user.has_role("edit_suggestion"): abort(401) # try to unlock unlocked = lock.unlock(object_type, object_id, current_user.id) # if we couldn't unlock, this is a bad request if not unlocked: abort(400) # otherwise, return success resp = make_response(json.dumps({"result" : "success"})) resp.mimetype = "application/json" return resp
def decorated_view(*args, **kwargs): # User must be logged if not _call_or_get(current_user.is_authenticated): # Redirect to the unauthenticated page return current_app.user_manager.unauthenticated_view_function() # User must have the required roles if not current_user.has_role(*role_names): # Redirect to the unauthorized page return current_app.user_manager.unauthorized_view_function() # Call the actual view return func(*args, **kwargs)
def journal_page(journal_id): # user must have the role "edit_journal" if not current_user.has_role("edit_journal"): abort(401) # get the journal, so we can check our permissions against it j = models.Journal.pull(journal_id) if j is None: abort(404) # user must be either the "admin.editor" of the journal, or the editor of the "admin.editor_group" # is the user the currently assigned editor of the journal? passed = False if j.editor == current_user.id: passed = True # now check whether the user is the editor of the editor group role = "associate_editor" eg = models.EditorGroup.pull_by_key("name", j.editor_group) if eg is not None and eg.editor == current_user.id: passed = True role = "editor" # if the user wasn't the editor or the owner of the editor group, unauthorised if not passed: abort(401) # attempt to get a lock on the object try: lockinfo = lock.lock("journal", journal_id, current_user.id) except lock.Locked as l: return render_template("editor/journal_locked.html", journal=j, lock=l.lock, edit_journal_page=True) if request.method == "GET": fc = formcontext.JournalFormFactory.get_form_context(role=role, source=j) return fc.render_template(edit_journal_page=True, lock=lockinfo) elif request.method == "POST": fc = formcontext.JournalFormFactory.get_form_context(role=role, form_data=request.form, source=j) if fc.validate(): try: fc.finalise() flash('Journal updated.', 'success') for a in fc.alert: flash_with_url(a, "success") return redirect(url_for("editor.journal_page", journal_id=j.id, _anchor='done')) except formcontext.FormContextException as e: flash(e.message) return redirect(url_for("editor.journal_page", journal_id=j.id, _anchor='cannot_edit')) else: return fc.render_template(edit_journal_page=True, lock=lockinfo)
def admin_required(): admin_logger = logging.getLogger('app.admin') if not current_user.is_authenticated: admin_logger.warning( 'an atempting entering from unauthenticated user: %s', request.remote_addr, ) abort(403) if not current_user.has_role('admin'): admin_logger.warning( 'an atempting entering from non-permissive user: %s', current_user.id ) abort(403)
def can_access_file_number(file_number, uid=None): if current_user and current_user.is_authenticated and current_user.has_role('admin', 'developer', 'advocate', 'trainer'): return True if uid is None: if has_request_context() and 'uid' in session: uid = session.get('uid', None) else: uid = docassemble.base.functions.get_uid() if uid is None: raise Exception("can_access_file_number: uid not defined") upload = Uploads.query.filter(and_(Uploads.indexno == file_number, or_(Uploads.key == uid, Uploads.private == False))).first() if upload: return True return False