def timesheet(): user, payperiod = process_timesheet_request() if not user: return redirect(url_for("timesheet")) if not payperiod: return redirect(url_for("manage_payperiods")) navigation = {'next': payperiod.get_next(), 'previous': payperiod.get_previous()} timesheet = get_timesheet(user, payperiod) logged_hours = get_logged_hours(timesheet) date_headers = payperiod.get_headers() # u#_c#_y#_m#_d# if request.method == 'POST': has_errors = False if current_user is not user: if not current_user.has_role("ts_edit_other"): flash("You do not have permission to edit other timesheets") has_errors = True if not current_user.has_role("ts_edit"): flash("You do not have permission to edit timesheets!") has_errors = True if timesheet.submitted: flash("You cannot modify a timesheet that has been submitted!") has_errors = True if has_errors: return redirect(url_for("timesheet")) conversion_error = False for customer in logged_hours: for logged_hour in logged_hours[customer]: field = "u%s_c%s_%s" % (user.id, customer.id, logged_hour.day.strftime("y%y_m%m_d%d")) value = request.values[field] if value == "": value = 0 else: try: value = float(request.values[field]) except: value = 0 conversion_error = True logged_hour.hours = value db.session.commit() log_event("timesheet", "Timesheet updated (%s)." % user.username) flash("Timesheet has been updated!") if conversion_error: flash("An error occurred converting one or more timesheet values. Please doublecheck your timesheet") else: if 'submit' in request.values: timesheet.submitted = True if current_user.has_role("ts_approve"): timesheet.approved = True log_event("timesheet", "Timesheet submitted for %s" % user.username) log_event("approve", "Timesheet automatically approved for %s" % user.username) flash("Timesheet successfully submitted and automatically approved.") else: log_event("timesheet", "Timesheet submitted for %s" % user.username) flash("Timesheet successfully submitted. Now pending approval.") db.session.commit() return render_template("timesheet.html", logged_hours=logged_hours, payperiod=payperiod, navigation=navigation, user=user, date_headers=date_headers, timesheet=timesheet)
def is_accessible(self): if not current_user.is_authenticated(): return False if current_user.has_role('super_user'): return True else: if self.requires_super_user: return False all_permissions = list(self.permissions or []) if self.requires_admin: all_permissions.append('admin') return all(current_user.has_role(permission) for permission in all_permissions)
def is_accessible(self): if current_user.is_authenticated(): admin =Role.query.filter(Role.name=="Admin").first() print admin return current_user.has_role(admin) else: return False
def user(id): user_profile = UserProfile.get_or_404(id) app_config_form = None if current_user.has_role('admin'): app_config_form = forms.AppConfigForm(search_rate=user_profile.appconfig.get('search')) app_config_form.itemfetch_rate.data = user_profile.appconfig.get('item') app_config_form.migrate_rate.data = user_profile.appconfig.get('user_import') app_config_form.message_rate.data = user_profile.appconfig.get('send_message') app_config_form.suggest_rate.data = user_profile.appconfig.get('search_suggestions') app_config_form.ratings_rate.data = user_profile.appconfig.get('review') if user_profile.editable_by(current_user): user_profile_form = forms.UserProfileForm(name=user_profile.display_name, bio=user_profile.bio or '', ga_id=user_profile.ga_id, app_key=user_profile.app_key) if user_profile_form.validate_on_submit(): user_profile.name = user_profile_form.name.data user_profile.bio = user_profile_form.bio.data user_profile.ga_id = user_profile_form.ga_id.data if user_profile.app_key != user_profile_form.app_key.data: user_profile.reset_app_key() user_profile_form.app_key.data = user_profile.app_key user_profile.put() flash(_LT('Your profile has been updated!'), 'success') else: user_profile_form = None return render_template('user/user.html', user_profile=user_profile, user_profile_form=user_profile_form, title=user_profile.display_name, app_config_form=app_config_form)
def settings_emails(): """Main email settings. """ if current_user.has_role('protected'): return abort(404) # TODO: make this 403, handle template properly api = system_util.pillar_api() user = User.find(current_user.objectid, api=api) # Force creation of settings for the user (safely remove this code once # implemented on account creation level, and after adding settings to all # existing users) if not user.settings: user.settings = dict(email_communications=1) user.update(api=api) if user.settings.email_communications is None: user.settings.email_communications = 1 user.update(api=api) # Generate form form = UserSettingsEmailsForm( email_communications=user.settings.email_communications) if form.validate_on_submit(): try: user.settings.email_communications = form.email_communications.data user.update(api=api) flash("Profile updated", 'success') except sdk_exceptions.ResourceInvalid as e: message = json.loads(e.content) flash(message) return render_template('users/settings/emails.html', form=form, title='emails')
def is_accessible(self): admin = current_user.has_role("admin") if not admin: flask.flash("You do not have permission to view this site") logout_user() return admin
def file(partno, file): """ Sends the specified file, after performing some access checks. Only component_edit users may look at all revisions, all other may only see the latest revision """ try: pn = PartNumber(partno) except ValueError: abort(404) # a revision must be specified if pn.revision is None: abort(404) # ensure the object exists and the revision is valid obj = current_app.mongo.db.components.find_one_or_404(pn.base_number) # ensure the desired revision exists num_revisions = len(obj.get('revisions', list())) assert pn.revision_number is not None if pn.revision_number >= num_revisions: abort(404) pn.set_num_revisions(num_revisions) if pn.is_outdated() and not current_user.has_role('component_edit'): abort(403) # instruct werkzeug to stream the file dir = os.path.join(current_app.config['LPM_COMPONENT_FILES_DIR'], partno) return send_from_directory(dir, file)
def username(username): Account = AccountFactory.get_model() acc = Account.pull(username) if acc is None: try: acc = Account.pull_by_email(username) except exceptions.NonUniqueAccountException: flash("Permanent Error: these user credentials are invalid - please contact an administrator", "error") return redirect(url_for(("logut"))) if acc is None: abort(404) # actions on this page are only availble to the actual user, or a user with the edit-users role if current_user.id != acc.id or not current_user.has_role(app.config.get("ACCOUNT_EDIT_USERS_ROLE")): abort(401) # if this is a request for the user page, just render it if request.method == "GET": fc = AccountFactory.get_user_formcontext(acc) return fc.render_template() is_delete = request.method == "DELETE" or (request.method == "POST" and request.values.get("submit", False) == "Delete") if is_delete: # validate the delete if not current_user.check_password(request.values.get("password")): flash("Incorrect password", "error") fc = AccountFactory.get_user_formcontext(acc=acc) return fc.render_template() # if the password validates, go ahead and do it acc.remove() # Note we don't use the DAO's delete method - this allows the model to decide the delete behaviour _do_logout() flash('Account {x} deleted'.format(x=username), "success") return redirect(url_for(app.config.get("ACCOUNT_LOGOUT_REDIRECT_ROUTE", "index"))) if request.method == "POST": fc = AccountFactory.get_user_formcontext(acc=acc, form_data=request.form) # attempt to validate the form if not fc.validate(): flash("There was a problem when submitting the form", "error") return fc.render_template() # if the form validates, then check the legality of the submission try: fc.legal() except exceptions.AccountException as e: flash(e.message, "error") return fc.render_template() # if we get to here, then update the user record fc.finalise() # tell the user that everything is good flash("Account updated", "success") # end with a redirect because some details have changed return redirect(url_for("account.username", username=fc.target.email))
def taskorder(): invalid_request = False if 'logged_hour_id' not in request.values: invalid_request = True else: logged_hour = LoggedHours.query.get(request.values['logged_hour_id']) if logged_hour is None: invalid_request = True if invalid_request: return "Invalid Request: Missing or invalid logged hour ID." user = logged_hour.timesheet.user if current_user is not user: if not current_user.has_role("ts_edit_other"): return "You do no thave permission to edit other timesheets." form = TaskOrder(request.form, logged_hour) if request.method == "GET": return render_template("taskorder.html", form=form, logged_hour=logged_hour) if form.validate_on_submit(): if logged_hour.timesheet.submitted: return "You cannot update task orders of submitted timesheets." logged_hour.note = request.values['note'] db.session.commit() return "Task order saved." else: return "An unknown error occurred. Please try again."
def inner(*args, **kwargs): desired_role = self.__role_class.query.filter_by( name=role).first() current_user = self.get_user() if current_user and current_user.has_role(desired_role): return func(*args, **kwargs) raise Forbidden()
def process_timesheet_request(): user = current_user if 'user_id' in request.values: if current_user.id != request.values['user_id']: if not current_user.has_role("ts_view_other"): flash("You do not have permission to see other users timesheets.") user = False else: user_id = request.values['user_id'] user = User.query.filter_by(id=user_id).first() if user is None: flash("User not found.") user = False if 'payperiod_id' in request.values: get_payperiod = False payperiod = PayPeriod.query.get(request.values['payperiod_id']) if payperiod is None: flash("Invalid payperiod specified. Displaying current payperiod.") get_payperiod = True else: get_payperiod = True if get_payperiod: payperiod = get_current_payperiod() if payperiod is None: flash("No payperiod is set up for today. Please set up the payroll cycle!") return (user, payperiod)
def edit(project_url): api = system_util.pillar_api() # Fetch the Node or 404 try: project = Project.find_one({'where': {'url': project_url}}, api=api) # project = Project.find(project_url, api=api) except ResourceNotFound: abort(404) attach_project_pictures(project, api) form = ProjectForm( project_id=project._id, name=project.name, url=project.url, summary=project.summary, description=project.description, is_private=u'GET' not in project.permissions.world, category=project.category, status=project.status, ) if form.validate_on_submit(): project = Project.find(project._id, api=api) project.name = form.name.data project.url = form.url.data project.summary = form.summary.data project.description = form.description.data project.category = form.category.data project.status = form.status.data if form.picture_square.data: project.picture_square = form.picture_square.data if form.picture_header.data: project.picture_header = form.picture_header.data # Update world permissions from is_private checkbox if form.is_private.data: project.permissions.world = [] else: project.permissions.world = [u'GET'] project.update(api=api) # Reattach the pictures attach_project_pictures(project, api) else: if project.picture_square: form.picture_square.data = project.picture_square._id if project.picture_header: form.picture_header.data = project.picture_header._id # List of fields from the form that should be hidden to regular users if current_user.has_role('admin'): hidden_fields = [] else: hidden_fields = ['url', 'status', 'is_private', 'category'] return render_template('projects/edit.html', form=form, hidden_fields=hidden_fields, project=project, title="edit", api=api)
def index(): #current_app.logger.debug('debug') if 'inv' in request.args: inv_id = request.args.get('inv_id') grp_id = request.args.get('grp_id') e = Invitations.query.filter(Invitations.id == inv_id).first() if e.accepted == True: return 'this person is already registered and added into your group' if e.accepted == False: return redirect(url_for('frontend.register_after_invited', inv=1, inv_id=inv_id, grp_id=grp_id)) form = Getemail(request.form) if current_user.has_role('Admin'): return redirect(url_for('admin.index')) elif current_user.is_authenticated() and not current_user.has_role('Admin'): return redirect(url_for('user.index')) return render_template('index.html', form=form)
def details(partno): """ Shows the details about the given component - Only component_edit users may look at specific revisions - All other only see the latest revision """ try: pn = PartNumber(partno) except ValueError: abort(404) # redirect to the revisionless URL if the user cannot view outdated revisions if pn.revision is not None and not current_user.has_role('component_edit'): return redirect(url_for('components.details', partno=pn.base_number)) # ensure the object exists and the revision is valid obj = current_app.mongo.db.components.find_one_or_404(pn.base_number) # ensure the desired revision exists num_revisions = len(obj.get('revisions', list())) if pn.revision_number is not None and pn.revision_number >= num_revisions: abort(404) pn.set_num_revisions(num_revisions) files = _get_files(pn.id) preview_file = None for file in files: if file.startswith('preview.'): preview_file = file break return render_template('components/details.html', data=obj, partno=pn, files=files, preview_file=preview_file)
def index(): if not app.config.get("ACCOUNT_LIST_USERS", False): abort(404) if not current_user.has_role( app.config.get("ACCOUNT_LIST_USERS_ROLE", "list_users")): abort(401) return render_template('account/users.html')
def profile(): """Displays a users's documents and profile information, as well as available invite codes if user is admin.""" codes = None if current_user.has_role('admin'): codes = InviteCode.query.filter_by(available=True).all() return render_template('profile.html', user=current_user, docs=current_user.documents, codes=codes)
def dashboard(): u = User.objects(id=current_user.id).first() if current_user.has_role('HR Manager'): p = Package.objects(manager=u).first() return redirect(url_for('package_view', package_id=str(p.id))) sub = Subscription.objects(user=u).first() return render_template('dashboard.html', bookings=Booking.upcoming_bookings(sub))
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 pw_reset(username): if current_user.username == username or current_user.has_role('admin'): current_user.reset_password() flash("Passort was reset") next=request.args.get("next", None) return redirect(next) else: abort(403)
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.has_role('admin'): return True return False
def journals(): if not current_user.has_role("admin_journals"): abort(401) return render_template('admin/journals.html', search_page=True, facetviews=['journals'], admin_page=True )
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('root'))
def pw_reset(username): if current_user.username == username or current_user.has_role('admin'): current_user.reset_password() flash("Passort was reset") next = request.args.get("next", None) return redirect(next) else: abort(403)
def is_accessible(self): if not current_user.is_active or not current_user.is_authenticated: return False if current_user.has_role('Admin'): return True return False
def get_user(user_username): requiredFields = {'name', 'last_name', 'gender', 'dni', 'email', 'birth_date', 'username'} if request.method == 'DELETE' and current_user.has_role('delete'): try: User.objects.get(username=user_username).delete() except Exception as e: logger.exception(e) return '', 500 return '', 200 elif request.method == 'PUT' and current_user.has_role('update'): data = request.json data = {key: data[key] for key in data if key in requiredFields} del data['username'] try: User.objects(username=user_username).update(upsert=False, multi=False, write_concern=None, full_result=True, **data) except Exception as e: logger.exception(e) return '', 500 return '', 200
def home(): if current_user.has_role('Studio Manager'): u = User.objects(id=current_user.id).first() s = Studio.objects(manager=u).first() return redirect(url_for('studio_view', studio_id=str(s.id))) if current_user.has_role('HR Manager'): u = User.objects(id=current_user.id).first() p = Package.objects(manager=u).first() return redirect(url_for('package_view', package_id=str(p.id))) if current_user.has_role('System Admin'): return redirect('/admin') results = Schedule.search(request.args.get('keyword'), request.args.get('date'), request.args.get('time')) return render_template('home.html', results=results, banner=_decide_banner(results))
def instances(self, where=None, sort=None): query = PrincipalManager.instances(self, where, sort) if current_user.has_role('network-admin') or current_user.has_role('gateway-admin'): if self.model == Network: query = query.filter_by(id=current_user.network_id) elif self.model in [ Gateway, User ]: query = query.filter_by(network_id=current_user.network_id) if current_user.has_role('network-admin'): if self.model == Voucher: query = query.join(Voucher.gateway).join(Gateway.network).filter(Network.id == current_user.network_id) if current_user.has_role('gateway-admin'): if self.model == Gateway: query = query.filter_by(id=current_user.gateway_id) elif self.model in [ User, Voucher ]: query = query.filter_by(gateway_id=current_user.gateway_id) return query
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 index(): """Render and process the main browser window.""" # Get the Gravatar Gravatar( current_app, size=100, rating='g', default='retro', force_default=False, use_ssl=False, base_url=None ) msg = None # Get the current version info from the website, and flash a message if # the user is out of date, and the check is enabled. if config.UPGRADE_CHECK_ENABLED: data = None url = '%s?version=%s' % (config.UPGRADE_CHECK_URL, config.APP_VERSION) current_app.logger.debug('Checking version data at: %s' % url) try: # Do not wait for more than 5 seconds. # It stuck on rendering the browser.html, while working in the # broken network. response = urlreq.urlopen(url, data, 5) current_app.logger.debug( 'Version check HTTP response code: %d' % response.getcode() ) if response.getcode() == 200: data = json.load(response) current_app.logger.debug('Response data: %s' % data) except: pass if data is not None: if data['pgadmin4']['version'] != config.APP_VERSION: msg = render_template( MODULE_NAME + "/upgrade.html", current_version=config.APP_VERSION, upgrade_version=data['pgadmin4']['version'], product_name=config.APP_NAME, download_url=data['pgadmin4']['download_url'] ) flash(msg, 'warning') return render_template( MODULE_NAME + "/index.html", username=current_user.email, is_admin=current_user.has_role("Administrator"), _=gettext )
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 not have any of the given roles if 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 decorated_view(*args, **kwargs): # User must be logged if not 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 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 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 _check_status(partno, current_status, new_status): pn = PartNumber(partno) partmap = current_app.config.get('LPM_ITEM_STATUS_MAP', dict()) map = partmap.get(pn.id) or partmap.get(pn.base_number) or partmap.get('default') or dict() if new_status not in map: raise ValueError("unknown status: '%s'" % new_status) definition = map.get(new_status) origins = definition.get('origins') if current_status not in origins: raise ValueError("Invalid status transition: from '%s' to '%s'" % (current_status, new_status)) role = definition.get('role') if role and not current_user.has_role(role): raise ValueError("insufficient permissions to do the status transition from '%s' to '%s'" % (current_status, new_status))
def details(ad_id): advert = models.Advert.pull(ad_id) if not advert: abort(404) if advert.is_deleted and not current_user.has_role("view_deleted"): abort(404) owner = False if current_user.id == advert.owner: owner = True if advert.is_deactivated and not owner and not current_user.has_role("view_deleted"): abort(404) return render_template( "advert/details.html", advert=advert, images_folder=app.config["IMAGES_FOLDER"], owner=owner, ad_id=ad_id, map_key=app.config.get("GOOGLE_MAP_API_KEY"), )
def suggestion_page(suggestion_id): # user must have the role "edit_journal" if not current_user.has_role("edit_suggestion"): abort(401) # get the journal, so we can check our permissions against it s = models.Suggestion.pull(suggestion_id) if s is None: abort(404) # flag which we can set to determine whether this user can access the editorial # features of the journal form editorial_available = False # 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 s.editor == current_user.id: passed = True # now check whether the user is the editor of the editor group # and simultaneously determine whether they have editorial rights # on this journal eg = models.EditorGroup.pull_by_key("name", s.editor_group) if eg is not None and eg.editor == current_user.id: passed = True editorial_available = True # if the user wasn't the editor or the owner of the editor group, unauthorised if not passed: abort(401) # create the list of allowable editors for this journal (the editor # and all the associates in this editor group) # egs = models.EditorGroup.groups_by_editor(current_user.id) editors = [current_user.id] editors += eg.associates editors = list(set(editors)) return suggestion_handler.request_handler( request, suggestion_id, redirect_route="editor.suggestion_page", template="editor/suggestion.html", locked_template="editor/suggestion_locked.html", editors=editors, editorial_available=editorial_available, status_options="editor")
def wrapper(*args, **kwargs): introles = roles if not isinstance(introles, tuple): introles = (introles,) valid = False if current_user.is_authenticated: for role in introles: if current_user.has_role(role): valid = True break if not valid: flash('insufficient privileges to access this page', 'danger') return login_manager.unauthorized() return f(*args, **kwargs)
def article_endpoint(article_id): if not current_user.has_role("delete_article"): abort(401) a = models.Article.pull(article_id) if a is None: abort(404) delete = request.values.get("delete", "false") if delete != "true": abort(400) a.snapshot() a.delete() # return a json response resp = make_response(json.dumps({"success" : True})) resp.mimetype = "application/json" return resp
def settings_billing(): """View the subscription status of a user """ if current_user.has_role('protected'): return abort(404) # TODO: make this 403, handle template properly api = system_util.pillar_api() user = User.find(current_user.objectid, api=api) groups = [] if user.groups: for group_id in user.groups: group = Group.find(group_id, api=api) groups.append(group.name) external_subscriptions_server = app.config['EXTERNAL_SUBSCRIPTIONS_MANAGEMENT_SERVER'] r = requests.get(external_subscriptions_server, params={'blenderid': user.email}) store_user = r.json() return render_template('users/settings/billing.html', store_user=store_user, groups=groups, title='billing')
def register(): if not app.config.get('PUBLIC_REGISTER', False) and not current_user.has_role("create_user"): abort(401) form = RegisterForm(request.form, csrf_enabled=False) if request.method == 'POST' and form.validate(): api_key = str(uuid.uuid4()) account = models.Account(id=form.w.data, email=form.n.data, api_key=api_key) account.set_password(form.s.data) account.save() flash( 'Account created for ' + account.id + '. If not listed below, refresh the page to catch up.', 'success') return redirect('/account') if request.method == 'POST' and not form.validate(): flash('Please correct the errors', 'error') return render_template('account/register.html', form=form)
def users_edit(user_id): if not current_user.has_role('admin'): return abort(403) api = system_util.pillar_api() user = User.find(user_id, api=api) form = UserEditForm() if form.validate_on_submit(): def get_groups(roles): """Return a set of role ids matching the group names provided""" groups_set = set() for system_role in roles: group = Group.find_one({'where': "name=='%s'" % system_role}, api=api) groups_set.add(group._id) return groups_set # Remove any of the default roles system_roles = set([role[0] for role in form.roles.choices]) system_groups = get_groups(system_roles) # Current user roles user_roles_list = user.roles if user.roles else [] user_roles = set(user_roles_list) user_groups = get_groups(user_roles_list) # Remove all form roles from current roles user_roles = list(user_roles.difference(system_roles)) user_groups = list(user_groups.difference(system_groups)) # Get the assigned roles system_roles_assigned = form.roles.data system_groups_assigned = get_groups(system_roles_assigned) # Reassign roles based on form.roles.data by adding them to existing roles user_roles += system_roles_assigned user_groups += list(get_groups(user_roles)) # Fetch the group for the assigned system roles user.roles = user_roles user.groups = user_groups user.update(api=api) else: form.roles.data = user.roles return render_template('users/edit_embed.html', user=user, form=form)
def reviews(): form = request.form offer_id = form.get('offer_id', None) offer = Offer.objects(id=offer_id).first() if offer: fullname = Markup(form.get('fullname')).striptags() email = Markup(form.get('email')).striptags() text = clear_tags_and_make_lines(form.get('review')) rating = Markup(form.get('rating')).striptags() try: rating = int(rating) except (TypeError, ValueError): rating = 0 review = Review(offer=offer, fullname=fullname, email=email, text=text, rating=rating) if current_user.is_authenticated and current_user.has_role('admin'): review.is_moderated = True review.save() userinfo = session.get('userinfo', None) if userinfo: if not userinfo.get('fullname', None): userinfo['fullname'] = fullname if not userinfo.get('email', None): userinfo['email'] = email else: userinfo = dict(fullname=fullname, email=email) session['userinfo'] = userinfo return json.dumps(dict(hello='world'))
def settings_profile(): """Profile view and edit page. This is a temporary implementation. """ if current_user.has_role('protected'): return abort(404) # TODO: make this 403, handle template properly api = system_util.pillar_api() user = User.find(current_user.objectid, api=api) form = UserProfileForm( full_name=user.full_name, username=user.username) if form.validate_on_submit(): try: user.full_name = form.full_name.data user.username = form.username.data user.update(api=api) flash("Profile updated", 'success') except sdk_exceptions.ResourceInvalid as e: message = json.loads(e.content) flash(message) return render_template('users/settings/profile.html', form=form, title='profile')
def request_handler(request, journal_id, redirect_route="admin.journal_page", template="admin/journal.html", locked_template="admin/journal_locked.html", activate_deactivate=False, group_editable=False, editors=None, editorial_available=False): # check our permissions if not current_user.has_role("edit_journal"): abort(401) j = get_journal(journal_id) if j is None: abort(404) # 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(locked_template, journal=j, lock=l.lock, edit_journal_page=True) current_info = models.ObjectDict(JournalFormXWalk.obj2form(j)) form = JournalForm(request.form, current_info) current_country = xwalk.get_country_code(j.bibjson().country) if current_country not in country_options_two_char_code_index: # couldn't find it, better warn the user to look for it # themselves country_help_text = "This journal's country has been recorded as \"{country}\". Please select it in the Country menu.".format( country=current_country) else: country_help_text = '' form.country.description = '<span class="red">' + country_help_text + '</span>' # add the contents of a few fields to their descriptions since select2 autocomplete # would otherwise obscure the full values if form.publisher.data: if not form.publisher.description: form.publisher.description = 'Full contents: ' + form.publisher.data else: form.publisher.description += '<br><br>Full contents: ' + form.publisher.data if form.society_institution.data: if not form.society_institution.description: form.society_institution.description = 'Full contents: ' + form.society_institution.data else: form.society_institution.description += '<br><br>Full contents: ' + form.society_institution.data if form.platform.data: if not form.platform.description: form.platform.description = 'Full contents: ' + form.platform.data else: form.platform.description += '<br><br>Full contents: ' + form.platform.data first_field_with_error = '' if editors is not None: form.editor.choices = [("", "Choose an editor") ] + [(editor, editor) for editor in editors] else: if j.editor is not None: form.editor.choices = [(j.editor, j.editor)] else: form.editor.choices = [("", "")] if request.method == 'POST': if form.make_all_fields_optional.data: valid = True else: valid = form.validate() if valid: # even though you can only edit journals right now, keeping the same # method as editing suggestions (i.e. creating a new object # and editing its properties) email_editor = False if group_editable: email_editor = JournalFormXWalk.is_new_editor_group(form, j) email_associate = False if editorial_available: email_associate = JournalFormXWalk.is_new_editor(form, j) # do the core crosswalk journal = JournalFormXWalk.form2obj(form, existing_journal=j) # some of the properties (id, in_doaj, etc.) have to be carried over # otherwise they implicitly end up getting changed to their defaults # when a journal gets edited (e.g. it always gets taken out of DOAJ) # if we don't copy over the in_doaj attribute to the new journal object journal['id'] = j['id'] created_date = j.created_date if j.created_date else datetime.now( ).strftime("%Y-%m-%dT%H:%M:%SZ") journal.set_created(created_date) journal.bibjson().active = j.is_in_doaj() journal.set_in_doaj(j.is_in_doaj()) if ((journal.owner is None or journal.owner == "") and (j.owner is not None)) or not current_user.has_role("admin"): journal.set_owner(j.owner) if not group_editable or not editorial_available: journal.set_editor_group(j.editor_group) if not editorial_available: journal.set_editor(j.editor) # FIXME: probably should check that the editor is in the editor_group and remove if not journal.save() flash('Journal updated.', 'success') # only actually send the email when we've successfully processed the form if email_editor: send_editor_group_email(journal) if email_associate: send_editor_email(journal) return redirect( url_for(redirect_route, journal_id=journal_id, _anchor='done')) # meaningless anchor to replace #first_problem used on the form # anchors persist between 3xx redirects to the same resource else: for field in form: # in order of definition of fields, so the order of rendering should be (manually) kept the same as the order of definition for this to work if field.errors: first_field_with_error = field.short_name break return render_template( template, form=form, first_field_with_error=first_field_with_error, q_numbers=xrange(1, 10000).__iter__( ), # a generator for the purpose of displaying numbered questions other_val=other_val, digital_archiving_policy_specific_library_value= digital_archiving_policy_specific_library_value, edit_journal_page=True, admin_page=True, journal=j, subjectstr=subjects2str(j.bibjson().subjects()), lcc_jstree=json.dumps(lcc_jstree), activate_deactivate=activate_deactivate, group_editable=group_editable, editorial_available=editorial_available, lock=lockinfo)
def form2obj(form, existing_journal): journal = Journal() bibjson = journal.bibjson() # The if statements that wrap practically every field are there due to this # form being used to edit old journals which don't necessarily have most of # this info. # It also allows admins to delete the contents of any field if they wish, # by ticking the "Allow incomplete form" checkbox and deleting the contents # of that field. The if condition(s) will then *not* add the relevant field to the # new journal object being constructed. # add_url in the journal model has a safeguard against empty URL-s. if form.title.data: bibjson.title = form.title.data bibjson.add_url(form.url.data, urltype='homepage') if form.alternative_title.data: bibjson.alternative_title = form.alternative_title.data if form.pissn.data: bibjson.add_identifier(bibjson.P_ISSN, form.pissn.data) if form.eissn.data: bibjson.add_identifier(bibjson.E_ISSN, form.eissn.data) if form.publisher.data: bibjson.publisher = form.publisher.data if form.society_institution.data: bibjson.institution = form.society_institution.data if form.platform.data: bibjson.provider = form.platform.data if form.contact_name.data or form.contact_email.data: journal.add_contact(form.contact_name.data, form.contact_email.data) if form.country.data: bibjson.country = form.country.data if forms.interpret_special(form.processing_charges.data): bibjson.set_apc(form.processing_charges_currency.data, form.processing_charges_amount.data) if forms.interpret_special(form.submission_charges.data): bibjson.set_submission_charges( form.submission_charges_currency.data, form.submission_charges_amount.data) if forms.interpret_special(form.waiver_policy.data): bibjson.add_url(form.waiver_policy_url.data, 'waiver_policy') # checkboxes if forms.interpret_special(form.digital_archiving_policy.data ) or form.digital_archiving_policy_url.data: archiving_policies = forms.interpret_special( form.digital_archiving_policy.data) archiving_policies = forms.interpret_other( archiving_policies, form.digital_archiving_policy_other.data, store_other_label=True) archiving_policies = forms.interpret_other( archiving_policies, form.digital_archiving_policy_library.data, forms.digital_archiving_policy_specific_library_value, store_other_label=True) bibjson.set_archiving_policy( archiving_policies, form.digital_archiving_policy_url.data) if form.crawl_permission.data and form.crawl_permission.data != 'None': bibjson.allows_fulltext_indexing = forms.interpret_special( form.crawl_permission.data) # just binary # checkboxes article_ids = forms.interpret_special(form.article_identifiers.data) article_ids = forms.interpret_other( article_ids, form.article_identifiers_other.data) if article_ids: bibjson.persistent_identifier_scheme = article_ids if (form.download_statistics.data and form.download_statistics.data != 'None') or form.download_statistics_url.data: bibjson.set_article_statistics( form.download_statistics_url.data, forms.interpret_special(form.download_statistics.data)) if form.first_fulltext_oa_year.data: bibjson.set_oa_start(year=form.first_fulltext_oa_year.data) # checkboxes fulltext_format = forms.interpret_other( form.fulltext_format.data, form.fulltext_format_other.data) if fulltext_format: bibjson.format = fulltext_format if form.keywords.data: bibjson.set_keywords(form.keywords.data) # tag list field if form.languages.data: bibjson.set_language(form.languages.data ) # select multiple field - gives a list back bibjson.add_url(form.editorial_board_url.data, urltype='editorial_board') if form.review_process.data or form.review_process_url.data: bibjson.set_editorial_review(form.review_process.data, form.review_process_url.data) bibjson.add_url(form.aims_scope_url.data, urltype='aims_scope') bibjson.add_url(form.instructions_authors_url.data, urltype='author_instructions') if (form.plagiarism_screening.data and form.plagiarism_screening.data != 'None') or form.plagiarism_screening_url.data: bibjson.set_plagiarism_detection( form.plagiarism_screening_url.data, has_detection=forms.interpret_special( form.plagiarism_screening.data)) if form.publication_time.data: bibjson.publication_time = form.publication_time.data bibjson.add_url(form.oa_statement_url.data, urltype='oa_statement') license_type = forms.interpret_other(form.license.data, form.license_other.data) if forms.interpret_special(license_type): # "None" and "False" as strings like they come out of the WTForms processing) # would get interpreted correctly by this check, so "None" licenses should not appear if license_type in licenses: by = licenses[license_type]['BY'] nc = licenses[license_type]['NC'] nd = licenses[license_type]['ND'] sa = licenses[license_type]['SA'] license_title = licenses[license_type]['title'] elif form.license_checkbox.data: by = True if 'BY' in form.license_checkbox.data else False nc = True if 'NC' in form.license_checkbox.data else False nd = True if 'ND' in form.license_checkbox.data else False sa = True if 'SA' in form.license_checkbox.data else False license_title = license_type else: by = None nc = None nd = None sa = None license_title = license_type bibjson.set_license( license_title, license_type, url=form.license_url.data, open_access=forms.interpret_special(form.open_access.data), by=by, nc=nc, nd=nd, sa=sa, embedded=forms.interpret_special(form.license_embedded.data), embedded_example_url=form.license_embedded_url.data) # checkboxes deposit_policies = forms.interpret_special( form.deposit_policy.data) # need empty list if it's just "None" deposit_policies = forms.interpret_other( deposit_policies, form.deposit_policy_other.data) if deposit_policies: bibjson.deposit_policy = deposit_policies if form.copyright.data and form.copyright.data != 'None': holds_copyright = forms.interpret_other( forms.interpret_special(form.copyright.data), form.copyright_other.data) bibjson.set_author_copyright(form.copyright_url.data, holds_copyright=holds_copyright) if form.publishing_rights.data and form.publishing_rights.data != 'None': publishing_rights = forms.interpret_other( forms.interpret_special(form.publishing_rights.data), form.publishing_rights_other.data) bibjson.set_author_publishing_rights( form.publishing_rights_url.data, holds_rights=publishing_rights) # need to copy over the notes from the existing journal object, if any, otherwise # the dates on all the notes will get reset to right now (i.e. last_updated) # since the journal object we're creating in this xwalk is a new, empty one journal.set_notes(existing_journal.notes()) # generate index of notes, just the text curnotes = [] for curnote in journal.notes(): curnotes.append(curnote['note']) # add any new notes formnotes = [] for formnote in form.notes.data: if formnote['note']: if formnote['note'] not in curnotes and formnote["note"] != "": journal.add_note(formnote['note']) # also generate another text index of notes, this time an index of the form notes formnotes.append(formnote['note']) if current_user.has_role("delete_note"): # delete all notes not coming back from the form, means they've been deleted # also if one of the saved notes is completely blank, delete it for curnote in journal.notes()[:]: if not curnote['note'] or curnote['note'] not in formnotes: journal.remove_note(curnote) new_subjects = [] for code in form.subject.data: sobj = { "scheme": 'LCC', "term": lcc.lookup_code(code), "code": code } new_subjects.append(sobj) bibjson.set_subjects(new_subjects) owner = form.owner.data.strip() if owner: journal.set_owner(owner) editor_group = form.editor_group.data.strip() if editor_group: journal.set_editor_group(editor_group) editor = form.editor.data.strip() if editor: journal.set_editor(editor) # old fields - only create them in the journal record if the values actually exist # need to use interpret_special in the test condition in case 'None' comes back from the form if getattr(form, 'author_pays', None): if forms.interpret_special(form.author_pays.data): bibjson.author_pays = form.author_pays.data if getattr(form, 'author_pays_url', None): if forms.interpret_special(form.author_pays_url.data): bibjson.author_pays_url = form.author_pays_url.data if getattr(form, 'oa_end_year', None): if forms.interpret_special(form.oa_end_year.data): bibjson.set_oa_end(form.oa_end_year.data) return journal
def form2obj(form, existing_suggestion=None): suggestion = models.Suggestion() bibjson = suggestion.bibjson() if form.title.data: bibjson.title = form.title.data bibjson.add_url(form.url.data, urltype='homepage') if form.alternative_title.data: bibjson.alternative_title = form.alternative_title.data if form.pissn.data: bibjson.add_identifier(bibjson.P_ISSN, form.pissn.data) if form.eissn.data: bibjson.add_identifier(bibjson.E_ISSN, form.eissn.data) if form.publisher.data: bibjson.publisher = form.publisher.data if form.society_institution.data: bibjson.institution = form.society_institution.data if form.platform.data: bibjson.provider = form.platform.data if form.contact_name.data or form.contact_email.data: suggestion.add_contact(form.contact_name.data, form.contact_email.data) if form.country.data: bibjson.country = form.country.data if forms.interpret_special(form.processing_charges.data): bibjson.set_apc(form.processing_charges_currency.data, form.processing_charges_amount.data) if forms.interpret_special(form.submission_charges.data): bibjson.set_submission_charges(form.submission_charges_currency.data, form.submission_charges_amount.data) suggestion.set_articles_last_year(form.articles_last_year.data, form.articles_last_year_url.data) if forms.interpret_special(form.waiver_policy.data): bibjson.add_url(form.waiver_policy_url.data, 'waiver_policy') # checkboxes if forms.interpret_special(form.digital_archiving_policy.data) or form.digital_archiving_policy_url.data: archiving_policies = forms.interpret_special(form.digital_archiving_policy.data) archiving_policies = forms.interpret_other(archiving_policies, form.digital_archiving_policy_other.data, store_other_label=True) archiving_policies = forms.interpret_other(archiving_policies, form.digital_archiving_policy_library.data, forms.digital_archiving_policy_specific_library_value, store_other_label=True) bibjson.set_archiving_policy(archiving_policies, form.digital_archiving_policy_url.data) if form.crawl_permission.data and form.crawl_permission.data != 'None': bibjson.allows_fulltext_indexing = forms.interpret_special(form.crawl_permission.data) # just binary # checkboxes article_ids = forms.interpret_special(form.article_identifiers.data) article_ids = forms.interpret_other(article_ids, form.article_identifiers_other.data) if article_ids: bibjson.persistent_identifier_scheme = article_ids if form.metadata_provision.data and form.metadata_provision.data != 'None': suggestion.article_metadata = forms.interpret_special(form.metadata_provision.data) # just binary if (form.download_statistics.data and form.download_statistics.data != 'None') or form.download_statistics_url.data: bibjson.set_article_statistics(form.download_statistics_url.data, forms.interpret_special(form.download_statistics.data)) if form.first_fulltext_oa_year.data: bibjson.set_oa_start(year=form.first_fulltext_oa_year.data) # checkboxes fulltext_format = forms.interpret_other(form.fulltext_format.data, form.fulltext_format_other.data) if fulltext_format: bibjson.format = fulltext_format if form.keywords.data: bibjson.set_keywords(form.keywords.data) # tag list field if form.languages.data: bibjson.set_language(form.languages.data) # select multiple field - gives a list back bibjson.add_url(form.editorial_board_url.data, urltype='editorial_board') if form.review_process.data or form.review_process_url.data: bibjson.set_editorial_review(form.review_process.data, form.review_process_url.data) bibjson.add_url(form.aims_scope_url.data, urltype='aims_scope') bibjson.add_url(form.instructions_authors_url.data, urltype='author_instructions') if (form.plagiarism_screening.data and form.plagiarism_screening.data != 'None') or form.plagiarism_screening_url.data: bibjson.set_plagiarism_detection( form.plagiarism_screening_url.data, has_detection=forms.interpret_special(form.plagiarism_screening.data) ) if form.publication_time.data: bibjson.publication_time = form.publication_time.data bibjson.add_url(form.oa_statement_url.data, urltype='oa_statement') license_type = forms.interpret_other(form.license.data, form.license_other.data) if forms.interpret_special(license_type): # "None" and "False" as strings like they come out of the WTForms processing) # would get interpreted correctly by this check, so "None" licenses should not appear if license_type in licenses: by = licenses[license_type]['BY'] nc = licenses[license_type]['NC'] nd = licenses[license_type]['ND'] sa = licenses[license_type]['SA'] license_title = licenses[license_type]['title'] elif form.license_checkbox.data: by = True if 'BY' in form.license_checkbox.data else False nc = True if 'NC' in form.license_checkbox.data else False nd = True if 'ND' in form.license_checkbox.data else False sa = True if 'SA' in form.license_checkbox.data else False license_title = license_type else: by = None; nc = None; nd = None; sa = None; license_title = license_type bibjson.set_license( license_title, license_type, url=form.license_url.data, open_access=forms.interpret_special(form.open_access.data), by=by, nc=nc, nd=nd, sa=sa, embedded=forms.interpret_special(form.license_embedded.data), embedded_example_url=form.license_embedded_url.data ) # checkboxes deposit_policies = forms.interpret_special(form.deposit_policy.data) # need empty list if it's just "None" deposit_policies = forms.interpret_other(deposit_policies, form.deposit_policy_other.data) if deposit_policies: bibjson.deposit_policy = deposit_policies if form.copyright.data and form.copyright.data != 'None': holds_copyright = forms.interpret_other( forms.interpret_special(form.copyright.data), form.copyright_other.data ) bibjson.set_author_copyright(form.copyright_url.data, holds_copyright=holds_copyright) if form.publishing_rights.data and form.publishing_rights.data != 'None': publishing_rights = forms.interpret_other( forms.interpret_special(form.publishing_rights.data), form.publishing_rights_other.data ) bibjson.set_author_publishing_rights(form.publishing_rights_url.data, holds_rights=publishing_rights) if form.suggester_name.data or form.suggester_email.data: suggestion.set_suggester(form.suggester_name.data, form.suggester_email.data) # admin stuff if getattr(form, 'application_status', None): suggestion.set_application_status(form.application_status.data) if getattr(form, 'notes', None): # need to copy over the notes from the existing suggestion object, if any, otherwise # the dates on all the notes will get reset to right now (i.e. last_updated) # since the suggestion object we're creating in this xwalk is a new, empty one if existing_suggestion: suggestion.set_notes(existing_suggestion.notes()) # generate index of notes, just the text curnotes = [] for curnote in suggestion.notes(): curnotes.append(curnote['note']) # add any new notes formnotes = [] for formnote in form.notes.data: if formnote['note']: if formnote['note'] not in curnotes and formnote["note"] != "": suggestion.add_note(formnote['note']) # also generate another text index of notes, this time an index of the form notes formnotes.append(formnote['note']) if current_user.has_role("delete_note"): # delete all notes not coming back from the form, means they've been deleted # also if one of the saved notes is completely blank, delete it for curnote in suggestion.notes()[:]: if not curnote['note'] or curnote['note'] not in formnotes: suggestion.remove_note(curnote) if getattr(form, 'subject', None): new_subjects = [] for code in form.subject.data: sobj = {"scheme": 'LCC', "term": lcc.lookup_code(code), "code": code} new_subjects.append(sobj) bibjson.set_subjects(new_subjects) if getattr(form, 'owner', None): owns = form.owner.data.strip() if owns: suggestion.set_owner(form.owner.data.strip()) if getattr(form, 'editor_group', None): editor_group = form.editor_group.data.strip() if editor_group: suggestion.set_editor_group(editor_group) if getattr(form, "editor", None): editor = form.editor.data.strip() if editor: suggestion.set_editor(editor) return suggestion
def suggestion_form(form, request, template_name, existing_suggestion=None, success_url=None, process_the_form=True, group_editable=False, editorial_available=False, redirect_route=None, lock=None, **kwargs): first_field_with_error = '' #import json #print json.dumps(request.form, indent=3) #import json #print json.dumps(form.data, indent=3) # the code below will output only submitted values which were truthy # useful for debugging the form itself without getting lost in the # 57-field object that gets created #print #print #for field in form: # #if field.data and field.data != 'None': # if field.short_name == 'subject': # print field.short_name, '::', field.data, ',', type(field.data) #print if request.method == 'POST': if not process_the_form: if existing_suggestion: # this is not a success, so we do not consider the success_url return redirect(url_for(redirect_route, suggestion_id=existing_suggestion.id, _anchor='cannot_edit')) else: #if form.make_all_fields_optional.data: # valid = True #else: # valid = form.validate() valid = form.validate() if valid: email_editor = False if group_editable: email_editor = SuggestionFormXWalk.is_new_editor_group(form, existing_suggestion) email_associate = False if editorial_available: email_associate = SuggestionFormXWalk.is_new_editor(form, existing_suggestion) # do the core crosswalk suggestion = SuggestionFormXWalk.form2obj(form, existing_suggestion) now = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") if not existing_suggestion: suggestion.suggested_on = now suggestion.set_application_status('pending') else: # copy over any important fields from the previous version of the object created_date = existing_suggestion.created_date if existing_suggestion.created_date else now suggestion.set_created(created_date) suggestion.suggested_on = existing_suggestion.suggested_on suggestion.data['id'] = existing_suggestion.data['id'] if ((suggestion.owner is None or suggestion.owner == "") and (existing_suggestion.owner is not None)) or not current_user.has_role("admin"): suggestion.set_owner(existing_suggestion.owner) if not group_editable or not editorial_available: suggestion.set_editor_group(existing_suggestion.editor_group) if not editorial_available: suggestion.set_editor(existing_suggestion.editor) # FIXME: probably should check that the editor is in the editor_group and remove if not # the code below can be used to quickly debug objects which # fail to serialise as JSON - there should be none of those # in the suggestion! ''' import json for thing in suggestion.data: try: if thing == 'bibjson': bibjson = suggestion.bibjson().bibjson for thing2 in bibjson: try: print json.dumps(bibjson[thing2]) except TypeError as e: print 'This is it:',thing2 print e print print json.dumps(bibjson[thing2]) except TypeError as e: print 'This is it:',thing print e print ''' # the code below produces a dump of the object returned by # the crosswalk ''' import json print print print 'Now all the data!' print json.dumps(suggestion.data, indent=3) ''' suggestion.save() if existing_suggestion: flash('Application updated.', 'success') if suggestion.application_status == 'accepted': # this suggestion is just getting accepted j = journal.suggestion2journal(suggestion) j.set_in_doaj(True) j.save() qobj = j.make_query(q=j.id) jurl = url_for('admin.admin_site_search') + '?source=' + json.dumps(qobj).replace('"', '"') flash_with_url('<a href="{url}" target="_blank">New journal created</a>.'.format(url=jurl), 'success') owner = create_account_on_suggestion_approval(suggestion, j) send_suggestion_approved_email(j.bibjson().title, owner.email) # only actually send the email when we've successfully processed the form if email_editor: send_editor_group_email(suggestion) if email_associate: send_editor_email(suggestion) if success_url: return redirect(success_url) else: return redirect(url_for(redirect_route, suggestion_id=suggestion.id, _anchor='done')) else: for field in form: # in order of definition of fields, so the order of rendering should be (manually) kept the same as the order of definition for this to work if field.errors: first_field_with_error = field.short_name print "field with error", first_field_with_error break return render_template( template_name, form=form, first_field_with_error=first_field_with_error, q_numbers=xrange(1, 10000).__iter__(), # a generator for the purpose of displaying numbered questions other_val=other_val, digital_archiving_policy_specific_library_value=digital_archiving_policy_specific_library_value, edit_suggestion_page=True, group_editable=group_editable, editorial_available=editorial_available, lock=lock, **kwargs )
def __call__(self, form, field): if current_user.has_role(self.role): super(RequiredIfRole, self).__call__(form, field)
def is_accessible(self): # Change this to do an admin check. return current_user.has_role('admin')
def users_index(): if not current_user.has_role('admin'): return abort(403) return render_template('users/index.html')
def query(path=None): # get the bits out of the path, and ensure that we have at least some parts to work with pathparts = path.strip('/').split('/') if len(pathparts) == 0: abort(400) # load the query route config and the path we are being requested for qrs = app.config.get("QUERY_ROUTE", {}) frag = request.path # get the configuration for this url route route_cfg = None for key in qrs: if frag.startswith("/" + key): route_cfg = qrs.get(key) break # if no route cfg is found this is not authorised if route_cfg is None: abort(401) # get the configuration for the specific index being queried index = pathparts[0] cfg = route_cfg.get(index) if cfg is None: abort(401) # does the user have to be authenticated if cfg.get("auth"): if current_user is None or current_user.is_anonymous(): abort(401) # if so, does the user require a role role = cfg.get("roles") if role is not None and not current_user.has_role(role): abort(401) # get the name of the model that will handle this query, and then look up # the class that will handle it dao_name = cfg.get("dao") dao_klass = plugin.load_class(dao_name) if dao_klass is None: abort(404) # now work out what kind of operation is being asked for # if _search is specified, then this is a normal query search = False by_id = None if len(pathparts) == 1 or (len(pathparts) == 2 and pathparts[1] == "_search"): search = True elif len(pathparts) == 2: if request.method == "POST": abort(401) by_id = pathparts[1] else: abort(400) resp = None if by_id is not None: rec = dao_klass.pull(by_id, wrap=False) resp = make_response(rec) elif search: q = Query() # if this is a POST, read the contents out of the body if request.method == "POST": q = Query(request.json) if request.json else Query(dict(request.form).keys()[-1]) # FIXME: does this actually work? # if there is a q param, make it into a query string query elif 'q' in request.values: s = request.values['q'] op = request.values.get('default_operator') q.query_string(s, op) # if there is a source param, load the json from it elif 'source' in request.values: q = Query(json.loads(urllib2.unquote(request.values['source']))) # now run the query through the filters filters = app.config.get("QUERY_FILTERS", {}) filter_names = cfg.get("filters", []) for filter_name in filter_names: # because of back-compat, we have to do a few tricky things here... # filter may be the name of a filter in the list of query filters fn = filters.get(filter_name) if fn is None: # filter may be the path to a function fn = plugin.load_function(filter_name) if fn is None: app.logger.info("Unable to load query filter for {x}".format(x=filter_name)) abort(500) fn(q) # finally send the query and return the response res = dao_klass.query(q=q.as_dict()) resp = make_response(json.dumps(res)) else: abort(400) resp.mimetype = "application/json" return resp
def is_accessible(self): return current_user.has_role("admin")