本文整理汇总了Python中pybossa.auth.ensure_authorized_to函数的典型用法代码示例。如果您正苦于以下问题:Python ensure_authorized_to函数的具体用法?Python ensure_authorized_to怎么用?Python ensure_authorized_to使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ensure_authorized_to函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: new_announcement
def new_announcement():
"""Create new announcement."""
def respond():
response = dict(template='admin/new_announcement.html',
title=gettext("Write a new post"),
form=form)
return handle_content_type(response)
form = AnnouncementForm()
del form.id
# project_sanitized, owner_sanitized = sanitize_project_owner(project, owner, current_user)
if request.method != 'POST':
ensure_authorized_to('create', Announcement())
return respond()
if not form.validate():
flash(gettext('Please correct the errors'), 'error')
return respond()
announcement = Announcement(title=form.title.data,
body=form.body.data,
published=form.published.data,
media_url=form.media_url.data,
user_id=current_user.id)
ensure_authorized_to('create', announcement)
announcement_repo.save(announcement)
msg_1 = gettext('Annnouncement created!')
markup = Markup('<i class="icon-ok"></i> {}')
flash(markup.format(msg_1), 'success')
return redirect_content_type(url_for('admin.announcement'))
开发者ID:fiorda,项目名称:pybossa,代码行数:34,代码来源:admin.py
示例2: categories
def categories():
"""List Categories."""
try:
if request.method == 'GET':
ensure_authorized_to('read', Category)
form = CategoryForm()
if request.method == 'POST':
ensure_authorized_to('create', Category)
form = CategoryForm(request.form)
del form.id
if form.validate():
slug = form.name.data.lower().replace(" ", "")
category = Category(name=form.name.data,
short_name=slug,
description=form.description.data)
project_repo.save_category(category)
cached_cat.reset()
msg = gettext("Category added")
flash(msg, 'success')
else:
flash(gettext('Please correct the errors'), 'error')
categories = cached_cat.get_all()
n_projects_per_category = dict()
for c in categories:
n_projects_per_category[c.short_name] = \
cached_projects.n_count(c.short_name)
return render_template('admin/categories.html',
title=gettext('Categories'),
categories=categories,
n_projects_per_category=n_projects_per_category,
form=form)
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:TMoneyZ,项目名称:pybossa,代码行数:35,代码来源:admin.py
示例3: put
def put(self, oid):
"""Update a single item in the DB.
:arg self: The class of the object to be updated
:arg integer oid: the ID of the object in the DB
:returns: An HTTP status code based on the output of the action.
More info about HTTP status codes for this action `here
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6>`_.
"""
try:
self.valid_args()
cls_name = self.__class__.__name__
repo = repos[cls_name]['repo']
query_func = repos[cls_name]['get']
existing = getattr(repo, query_func)(oid)
if existing is None:
raise NotFound
ensure_authorized_to('update', existing)
data = self._file_upload(request)
inst = self._update_instance(existing, repo,
repos,
new_upload=data)
self.refresh_cache(cls_name, oid)
return Response(json.dumps(inst.dictize()), 200,
mimetype='application/json')
except Exception as e:
return error.format_exception(
e,
target=self.__class__.__name__.lower(),
action='PUT')
开发者ID:fiorda,项目名称:pybossa,代码行数:32,代码来源:api_base.py
示例4: del_category
def del_category(id):
"""Delete a category."""
try:
category = project_repo.get_category(id)
if category:
if len(cached_cat.get_all()) > 1:
ensure_authorized_to('delete', category)
if request.method == 'GET':
return render_template('admin/del_category.html',
title=gettext('Delete Category'),
category=category)
if request.method == 'POST':
project_repo.delete_category(category)
msg = gettext("Category deleted")
flash(msg, 'success')
cached_cat.reset()
return redirect(url_for(".categories"))
else:
msg = gettext('Sorry, it is not possible to delete the only'
' available category. You can modify it, '
' click the edit button')
flash(msg, 'warning')
return redirect(url_for('.categories'))
else:
abort(404)
except HTTPException:
raise
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:TMoneyZ,项目名称:pybossa,代码行数:30,代码来源:admin.py
示例5: _create_instance_from_request
def _create_instance_from_request(self, data):
data = self.hateoas.remove_links(data)
inst = self.__class__(**data)
self._update_object(inst)
ensure_authorized_to('create', inst)
self._validate_instance(inst)
return inst
开发者ID:bluetropic,项目名称:pybossa,代码行数:7,代码来源:api_base.py
示例6: _create_json_response
def _create_json_response(self, query_result, oid):
if len(query_result) == 1 and query_result[0] is None:
raise abort(404)
items = []
for result in query_result:
# This is for n_favs orderby case
if not isinstance(result, DomainObject):
if 'n_favs' in result.keys():
result = result[0]
try:
if (result.__class__ != self.__class__):
(item, headline, rank) = result
else:
item = result
headline = None
rank = None
datum = self._create_dict_from_model(item)
if headline:
datum['headline'] = headline
if rank:
datum['rank'] = rank
ensure_authorized_to('read', item)
items.append(datum)
except (Forbidden, Unauthorized):
# Remove last added item, as it is 401 or 403
if len(items) > 0:
items.pop()
except Exception: # pragma: no cover
raise
if oid is not None:
ensure_authorized_to('read', query_result[0])
items = items[0]
return json.dumps(items)
开发者ID:fiorda,项目名称:pybossa,代码行数:33,代码来源:api_base.py
示例7: _file_delete
def _file_delete(self, request, obj):
"""Delete file object."""
cls_name = self.__class__.__name__.lower()
if cls_name in self.allowed_classes_upload:
keys = obj.info.keys()
if 'file_name' in keys and 'container' in keys:
ensure_authorized_to('delete', obj)
uploader.delete_file(obj.info['file_name'],
obj.info['container'])
开发者ID:fiorda,项目名称:pybossa,代码行数:9,代码来源:api_base.py
示例8: delete_announcement
def delete_announcement(id):
announcement = announcement_repo.get_by(id=id)
if announcement is None:
raise abort(404)
ensure_authorized_to('delete', announcement)
announcement_repo.delete(announcement)
msg_1 = gettext('Announcement deleted!')
markup = Markup('<i class="icon-ok"></i> {}')
flash(markup.format(msg_1), 'success')
return redirect_content_type(url_for('admin.announcement'))
开发者ID:fiorda,项目名称:pybossa,代码行数:11,代码来源:admin.py
示例9: _delete_instance
def _delete_instance(self, oid):
repo = repos[self.__class__.__name__]['repo']
query_func = repos[self.__class__.__name__]['get']
inst = getattr(repo, query_func)(oid)
if inst is None:
raise NotFound
ensure_authorized_to('delete', inst)
self._log_changes(inst, None)
delete_func = repos[self.__class__.__name__]['delete']
getattr(repo, delete_func)(inst)
return inst
开发者ID:bluetropic,项目名称:pybossa,代码行数:11,代码来源:api_base.py
示例10: set_gravatar
def set_gravatar(name):
"""Set gravatar for a user."""
user = user_repo.get_by(name=name)
if not user:
abort(404)
ensure_authorized_to('update', user)
gravatar.set(user)
flash(gettext('Your avatar has been updated! It may \
take some minutes to refresh...'), 'success')
return redirect(url_for('account.update_profile', name=user.name))
开发者ID:opensensorsdata,项目名称:pybossa-gravatar,代码行数:13,代码来源:view.py
示例11: get
def get(self, token):
try:
ensure_authorized_to('read', self._resource_name, token=token)
user_tokens = self._get_all_tokens()
if token:
response = self._get_token(token, user_tokens)
else:
response = user_tokens
return Response(json.dumps(response), mimetype='application/json')
except Exception as e:
return error.format_exception(
e,
target=self._resource_name,
action='GET')
开发者ID:pkdevbox,项目名称:pybossa,代码行数:14,代码来源:token.py
示例12: sync
def sync(short_name):
"""Sync a project with a GitHub repo."""
project = project_repo.get_by_shortname(short_name)
if not project: # pragma: no cover
abort(404)
ensure_authorized_to('update', project)
form = GitHubURLForm(request.form)
if request.method == 'POST' and form.validate():
github_url = form.github_url.data
return redirect(url_for('.import_repo', github_url=github_url,
short_name=project.short_name))
elif request.method == 'POST': # pragma: no cover
flash(gettext('Please correct the errors'), 'error')
return render_template('projects/github/sync.html', form=form,
project=project)
开发者ID:alexandermendes,项目名称:pybossa-github-builder,代码行数:15,代码来源:view.py
示例13: add_admin
def add_admin(user_id=None):
"""Add admin flag for user_id."""
try:
if user_id:
user = user_repo.get(user_id)
if user:
ensure_authorized_to('update', user)
user.admin = True
user_repo.update(user)
return redirect(url_for(".users"))
else:
msg = "User not found"
return format_error(msg, 404)
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:TMoneyZ,项目名称:pybossa,代码行数:16,代码来源:admin.py
示例14: _create_json_response
def _create_json_response(self, query_result, oid):
if len(query_result) == 1 and query_result[0] is None:
raise abort(404)
items = []
for item in query_result:
try:
items.append(self._create_dict_from_model(item))
ensure_authorized_to('read', item)
except (Forbidden, Unauthorized):
# Remove last added item, as it is 401 or 403
items.pop()
except Exception: # pragma: no cover
raise
if oid is not None:
ensure_authorized_to('read', query_result[0])
items = items[0]
return json.dumps(items)
开发者ID:bluetropic,项目名称:pybossa,代码行数:17,代码来源:api_base.py
示例15: reset_api_key
def reset_api_key(name):
"""
Reset API-KEY for user.
Returns a Jinja2 template.
"""
user = user_repo.get_by_name(name)
if not user:
return abort(404)
ensure_authorized_to('update', user)
user.api_key = model.make_uuid()
user_repo.update(user)
cached_users.delete_user_summary(user.name)
msg = gettext('New API-KEY generated')
flash(msg, 'success')
return redirect(url_for('account.profile', name=name))
开发者ID:bluetropic,项目名称:pybossa,代码行数:17,代码来源:account.py
示例16: featured
def featured(project_id=None):
"""List featured projects of PYBOSSA."""
try:
if request.method == 'GET':
categories = cached_cat.get_all()
projects = {}
for c in categories:
n_projects = cached_projects.n_count(category=c.short_name)
projects[c.short_name] = cached_projects.get(
category=c.short_name,
page=1,
per_page=n_projects)
response = dict(template = '/admin/projects.html',
projects=projects,
categories=categories,
form=dict(csrf=generate_csrf()))
return handle_content_type(response)
else:
project = project_repo.get(project_id)
if project:
ensure_authorized_to('update', project)
if request.method == 'POST':
if project.featured is True:
msg = "Project.id %s already featured" % project_id
return format_error(msg, 415)
cached_projects.reset()
project.featured = True
project_repo.update(project)
return json.dumps(project.dictize())
if request.method == 'DELETE':
if project.featured is False:
msg = 'Project.id %s is not featured' % project_id
return format_error(msg, 415)
cached_projects.reset()
project.featured = False
project_repo.update(project)
return json.dumps(project.dictize())
else:
msg = 'Project.id %s not found' % project_id
return format_error(msg, 404)
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:fiorda,项目名称:pybossa,代码行数:44,代码来源:admin.py
示例17: start_export
def start_export(name):
"""
Starts a export of all user data according to EU GDPR
Data will be available on GET /export after it is processed
"""
user = user_repo.get_by_name(name)
if not user:
return abort(404)
if user.id != current_user.id:
return abort(403)
ensure_authorized_to('update', user)
export_queue.enqueue(export_userdata,
user_id=user.id)
msg = gettext('GDPR export started')
flash(msg, 'success')
return redirect_content_type(url_for('account.profile', name=name))
开发者ID:keyinfluencerplus,项目名称:tinybee.ai,代码行数:19,代码来源:account.py
示例18: del_admin
def del_admin(user_id=None):
"""Del admin flag for user_id."""
try:
if user_id:
user = user_repo.get(user_id)
if user:
ensure_authorized_to('update', user)
user.admin = False
user_repo.update(user)
return redirect(url_for('.users'))
else:
msg = "User.id not found"
return format_error(msg, 404)
else: # pragma: no cover
msg = "User.id is missing for method del_admin"
return format_error(msg, 415)
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:TMoneyZ,项目名称:pybossa,代码行数:19,代码来源:admin.py
示例19: _file_upload
def _file_upload(self, data):
"""Method that must be overriden by the class to allow file uploads for
only a few classes."""
cls_name = self.__class__.__name__.lower()
content_type = 'multipart/form-data'
if (content_type in request.headers.get('Content-Type') and
cls_name in self.allowed_classes_upload):
tmp = dict()
for key in request.form.keys():
tmp[key] = request.form[key]
if isinstance(self, announcement.Announcement):
# don't check project id for announcements
ensure_authorized_to('create', self)
upload_method = current_app.config.get('UPLOAD_METHOD')
if request.files.get('file') is None:
raise AttributeError
_file = request.files['file']
container = "user_%s" % current_user.id
else:
ensure_authorized_to('create', self.__class__,
project_id=tmp['project_id'])
project = project_repo.get(tmp['project_id'])
upload_method = current_app.config.get('UPLOAD_METHOD')
if request.files.get('file') is None:
raise AttributeError
_file = request.files['file']
if current_user.admin:
container = "user_%s" % project.owner.id
else:
container = "user_%s" % current_user.id
uploader.upload_file(_file,
container=container)
file_url = get_avatar_url(upload_method,
_file.filename, container)
tmp['media_url'] = file_url
if tmp.get('info') is None:
tmp['info'] = dict()
tmp['info']['container'] = container
tmp['info']['file_name'] = _file.filename
return tmp
else:
return None
开发者ID:fiorda,项目名称:pybossa,代码行数:43,代码来源:api_base.py
示例20: update_category
def update_category(id):
"""Update a category."""
try:
category = project_repo.get_category(id)
if category:
ensure_authorized_to('update', category)
form = CategoryForm(obj=category)
form.populate_obj(category)
if request.method == 'GET':
response = dict(template='admin/update_category.html',
title=gettext('Update Category'),
category=category,
form=form)
return handle_content_type(response)
if request.method == 'POST':
form = CategoryForm(request.body)
if form.validate():
slug = form.name.data.lower().replace(" ", "")
new_category = Category(id=form.id.data,
name=form.name.data,
short_name=slug)
project_repo.update_category(new_category)
cached_cat.reset()
msg = gettext("Category updated")
flash(msg, 'success')
return redirect_content_type(url_for(".categories"))
else:
msg = gettext("Please correct the errors")
flash(msg, 'success')
response = dict(template='admin/update_category.html',
title=gettext('Update Category'),
category=category,
form=form)
return handle_content_type(response)
else:
abort(404)
except HTTPException:
raise
except Exception as e: # pragma: no cover
current_app.logger.error(e)
return abort(500)
开发者ID:fiorda,项目名称:pybossa,代码行数:41,代码来源:admin.py
注:本文中的pybossa.auth.ensure_authorized_to函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论