Here are the examples of the python api django.http.HttpResponseForbidden taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
170 Examples
5
Example 1
def process_response(self, request, response):
# If the response object is a vanilla 403 constructed with
# django.http.HttpResponseForbidden() then call our custom 403 view
# function
if isinstance(response, django.http.HttpResponseForbidden) and \
set(dir(response)) == set(dir(django.http.HttpResponseForbidden())):
import views
try:
return views.access_denied(request)
except django.template.TemplateDoesNotExist, e:
return views.fallback_403(request)
return response
3
Example 2
Project: django_linter Source File: func_views_fetching_db_objects_len.py
def product_list_view(request):
if request.is_authenticated():
ctx = {'products': Product.objects.all(),
'categories_count': len(Category.objects.all())}
return render(request, 'product_list.html', context=ctx)
else:
return HttpResponseForbidden()
3
Example 3
Project: CommunityCellularManager Source File: file_upload.py
def file_view(request, fname):
"""A view that echoes back what it receives."""
if not request.user.is_staff:
return HttpResponseForbidden()
if request.method != 'GET':
return HttpResponseBadRequest()
storage = DatabaseStorage()
f = storage.open(fname, 'rb')
if f is None:
return HttpResponseNotFound()
ftype, _ = mimetypes.guess_type(fname)
response = HttpResponse(f.read(), content_type=ftype or 'application/octet-stream')
response['Content-Disposition'] = 'inline; filename=%s' % fname
response['Content-Length'] = '%d' % f.size
return response
3
Example 4
Project: airmozilla Source File: views.py
def must_be_your_event(f):
@wraps(f)
def inner(request, id, **kwargs):
assert request.user.is_authenticated()
event = get_object_or_404(Event, pk=id)
if event.creator != request.user:
return http.HttpResponseForbidden(
"Not your event to meddle with"
)
return f(request, event, **kwargs)
return inner
3
Example 5
Project: cgstudiomap Source File: views.py
def with_origin(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
origin = request.META.get('HTTP_ORIGIN')
if not is_valid_origin(origin):
return HttpResponseForbidden()
response = func(request, *args, **kwargs)
response['Access-Control-Allow-Origin'] = origin
response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
return response
return wrapped
3
Example 6
Project: django-urlcrypt Source File: views.py
def rate_limit(num=60):
"""
Limits the number of requests made by a unique visitor to this view to num per minute.
"""
def decorator(func):
def wrapper(request, *args, **kwargs):
cache_key = 'rate_limit.%s' % request.session._session_key
added = cache.add(cache_key, 1, timeout=60)
if added:
num_tries = 1
else:
num_tries = cache.incr(cache_key, delta=1)
if num_tries > num:
raise HttpResponseForbidden("Rate Limit Exceeded")
return func(request, *args, **kwargs)
return wrapper
return decorator
3
Example 7
Project: frigg-hq Source File: decorators.py
def worker_token_required(view_func):
@csrf_exempt
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
token = request.META.get('HTTP_FRIGG_WORKER_TOKEN')
if token:
if token in getattr(settings, 'FRIGG_WORKER_TOKENS', []):
return view_func(request, *args, **kwargs)
return HttpResponseForbidden()
return _wrapped_view
3
Example 8
def get(self, request, pk):
if not request.user.is_staff:
return HttpResponseForbidden()
ctype = get_object_or_404(ContentType.objects, pk=pk).model_class()
if not issubclass(ctype, Ticket):
raise Http404()
result = [{'name': name, 'label': unicode(ctype._meta.get_field(name).verbose_name)} for name in ctype.get_fields()]
return HttpResponse(json.dumps(result),
content_type='text/json')
3
Example 9
Project: django-debug-toolbar-user-panel Source File: decorators.py
def debug_required(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if not getattr(settings, 'DEBUG_TOOLBAR_USER_DEBUG', settings.DEBUG):
return HttpResponseForbidden()
return fn(*args, **kwargs)
return wrapper
3
Example 10
Project: otm-core Source File: user.py
def update_profile_photo(request, user_id):
user = get_object_or_404(User, pk=user_id)
if user.pk != request.user.pk:
return HttpResponseForbidden()
return upload_user_photo(request, user)
3
Example 11
Project: tendenci Source File: views.py
def dispatch(self, request, *args, **kwargs):
try:
return super(RedirectToLoginMixin, self).dispatch(request, *args, **kwargs)
except PermissionDenied:
if not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(self.get_login_redirect_url())
else:
return HttpResponseForbidden()
3
Example 12
@require_POST
@csrf_exempt
def deauthorize_facebook_user(request):
signed_request = request.POST.get(u'signed_request', None)
if not signed_request:
return HttpResponseForbidden('403 Forbidden')
data = parse_signed_request(request, signed_request)
fb_uid = data['user_id']
fb_user = FacebookUser.objects.get(fb_uid=int(fb_uid))
fb_user.delete()
Metrics.facebook_user_deauthorized.record(request)
return HttpResponse('success')
3
Example 13
Project: dissemin Source File: views.py
@user_passes_test(is_authenticated)
def refetchResearcher(request, pk):
researcher = get_object_or_404(Researcher, pk=pk)
if researcher.user != request.user and not request.user.is_staff:
return HttpResponseForbidden("Not authorized to update papers for this researcher.")
from backend.tasks import fetch_everything_for_researcher
fetch_everything_for_researcher.delay(pk=pk)
return redirect(request.META['HTTP_REFERER'])
3
Example 14
Project: onlineweb4 Source File: views.py
@require_http_methods(["POST"])
@login_required
def vote(request):
m = get_active_meeting()
if m:
a = anonymous_voter(request.COOKIES.get('anon_voter'), request.user.username)
r = RegisteredVoter.objects.filter(user=request.user, meeting=m).first()
# If user is logged in
if a:
return handle_user_vote(request, m, a, r)
return HttpResponseForbidden()
3
Example 15
def permission_denied(request, template_name=None, extra_context={}):
"""
Default 403 handler.
Templates: `403.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
if template_name is None:
template_name = ('403.html',)
context = {
'request_path': request.path,
}
context.update(extra_context)
return HttpResponseForbidden(loader.render_to_string(template_name, context,
context_instance=RequestContext(request)))
3
Example 16
def require_login(request):
"""Return 403 if request is AJAX. Redirect to login page if not."""
if request.is_ajax():
return HttpResponseForbidden('Not logged in')
else:
return HttpResponseRedirect('/uzytkownicy/zaloguj') # next?=request.build_full_path())
3
Example 17
def render_to_response(self, context, **response_kwargs):
if hasattr(self, 'permission') and self.permission not in context:
return HttpResponseForbidden("You do not have permissions to access this content.")
return self.response_class(
request = self.request,
template = self.get_template_names(),
context = context,
**response_kwargs
)
3
Example 18
def permission_denied(request, title='Permission denied',
message='You do not have permission to perform the requested action.'):
"""
Returns an HttpResponseForbidden with a permission denied error
screen.
"""
return HttpResponseForbidden(loader.render_to_string(
'forum/permission_denied.html', {
'title': title,
'message': message,
}))
3
Example 19
def __call__(self, request):
"""
Handle an autocomplete request.
"""
self.request = request
if request.method not in self.allowed_methods:
return HttpResponseNotAllowed(self.allowed_methods)
if not self.is_authorized():
return HttpResponseForbidden()
results = self.get_result_queryset()
return self.get_response(results)
3
Example 20
Project: make.mozilla.org Source File: views.py
def verified_ownership(f):
def wrapped(request, event_hash):
event = get_object_or_404(models.Event, url_hash=event_hash)
if not event.verify_ownership(request.user):
return http.HttpResponseForbidden(u'sorry, you’re not allowed in')
return f(request, event)
return wrapped
3
Example 21
Project: evething Source File: account.py
def account_register(request):
"""Register Account"""
if not settings.ALLOW_REGISTRATION:
return HttpResponseForbidden()
if request.user.is_authenticated():
return redirect(reverse('home'))
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('home'))
else:
form = UserCreationForm()
return render(request, "registration/register.html", {
'form': form,
})
3
Example 22
Project: kobocat Source File: views.py
def readable_xform_required(func):
def _wrapper(request, username, id_string):
owner = get_object_or_404(User, username=username)
xform = get_object_or_404(owner.xforms, id_string=id_string)
if not has_permission(xform, owner, request):
return HttpResponseForbidden(_(u'Not shared.'))
return func(request, username, id_string)
return _wrapper
3
Example 23
def delete(self, request, user, resource_name):
resource = self.get_resource(request, user, resource_name)
# you can't delete protected resources
if resource.protected:
return HttpResponseForbidden()
depth = request.META.get('HTTP_DEPTH', 'infinity')
# return forbidden if there are still items in the collection and
# Depth is not 'infinity'
# this is not standard-compliant, but should increase security
if resource.collection and depth != 'infinity':
if resource.resource_set.count() > 0:
return HttpResponseForbidden()
resource.delete()
return HttpResponse(status=204)
3
Example 24
Project: wagtail Source File: collections.py
def post(self, request, instance_id):
self.instance = get_object_or_404(self.get_queryset(), id=instance_id)
collection_contents = self.get_collection_contents()
if collection_contents:
# collection is non-empty; refuse to delete it
return HttpResponseForbidden()
self.instance.delete()
messages.success(request, self.success_message.format(self.instance))
return redirect(self.index_url_name)
3
Example 25
def handler403(request):
if request.is_ajax():
return HttpResponse('403 Forbidden', status=403,
content_type='text/plain')
message = render_to_string('403.html',
context_instance=RequestContext(request))
return HttpResponseForbidden(message)
3
Example 26
Project: idea-color-themes Source File: themes.py
@view(path=r'^themes/download-all-archive/?')
def download_all_archive(request):
token_value = request.session.get('shopping_token', None)
if allow_download_all(token_value):
archive = get_all_themes_archive()
resp = http.HttpResponse(archive, mimetype='application/x-zip-compressed')
resp['Content-Disposition'] = 'attachment; filename=all-idea-color-themes.zip'
return resp
return HttpResponseForbidden()
3
Example 27
@method_decorator(login_required)
def post(self, request, pk):
link = get_object_or_404(Link, pk=pk)
if not request.user.get_profile().owns_project(link.project):
return HttpResponseForbidden()
link.delete()
if request.is_ajax():
return HttpResponse(status=204)
return redirect('projects_show', slug=link.project.slug)
3
Example 28
def dispatch(self, request, *args, **kwargs):
handler = super(DocuementEdit, self).dispatch(request, *args, **kwargs)
# Only allow editing if current user is owner
if self.object.uploader != request.user:
return HttpResponseForbidden('Du darfst keine fremden Uploads editieren.')
return handler
3
Example 29
Project: huxley Source File: views.py
def login_as_user(request, uid):
'''Log in as a particular user (admin use only).'''
try:
if not request.user.is_superuser:
return HttpResponseForbidden()
username = User.objects.get(id=uid).username
user = authenticate(username=username, password=settings.ADMIN_SECRET)
login(request, user)
return HttpResponseRedirect(reverse('www:index'))
except User.DoesNotExist:
return HttpResponseNotFound()
0
Example 30
Project: Django--an-app-at-a-time Source File: common.py
def process_request(self, request):
"""
Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW
"""
# Check for denied User-Agents
if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
logger.warning('Forbidden (User agent): %s', request.path,
extra={
'status_code': 403,
'request': request
}
)
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
# Check for a redirect based on settings.APPEND_SLASH
# and settings.PREPEND_WWW
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.PREPEND_WWW and old_url[0] and
not old_url[0].startswith('www.')):
new_url[0] = 'www.' + old_url[0]
# Append a slash if APPEND_SLASH is set and the URL doesn't have a
# trailing slash and there is no pattern for the current path
if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
urlconf = getattr(request, 'urlconf', None)
if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST':
raise RuntimeError((""
"You called this URL via POST, but the URL doesn't end "
"in a slash and you have APPEND_SLASH set. Django can't "
"redirect to the slash URL while maintaining POST data. "
"Change your form to point to %s%s (note the trailing "
"slash), or set APPEND_SLASH=False in your Django "
"settings.") % (new_url[0], new_url[1]))
if new_url == old_url:
# No redirects required.
return
if new_url[0]:
newurl = "%s://%s%s" % (
request.scheme,
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.META.get('QUERY_STRING', ''):
if six.PY3:
newurl += '?' + request.META['QUERY_STRING']
else:
# `query_string` is a bytestring. Appending it to the unicode
# string `newurl` will fail if it isn't ASCII-only. This isn't
# allowed; only broken software generates such query strings.
# Better drop the invalid query string than crash (#15152).
try:
newurl += '?' + request.META['QUERY_STRING'].decode()
except UnicodeDecodeError:
pass
return self.response_redirect_class(newurl)
0
Example 31
Project: PyClassLessons Source File: common.py
def process_request(self, request):
"""
Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW
"""
# Check for denied User-Agents
if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
logger.warning('Forbidden (User agent): %s', request.path,
extra={
'status_code': 403,
'request': request
}
)
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
# Check for a redirect based on settings.APPEND_SLASH
# and settings.PREPEND_WWW
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.PREPEND_WWW and old_url[0] and
not old_url[0].startswith('www.')):
new_url[0] = 'www.' + old_url[0]
# Append a slash if APPEND_SLASH is set and the URL doesn't have a
# trailing slash and there is no pattern for the current path
if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
urlconf = getattr(request, 'urlconf', None)
if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST':
raise RuntimeError((""
"You called this URL via POST, but the URL doesn't end "
"in a slash and you have APPEND_SLASH set. Django can't "
"redirect to the slash URL while maintaining POST data. "
"Change your form to point to %s%s (note the trailing "
"slash), or set APPEND_SLASH=False in your Django "
"settings.") % (new_url[0], new_url[1]))
if new_url == old_url:
# No redirects required.
return
if new_url[0]:
newurl = "%s://%s%s" % (
request.scheme,
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.META.get('QUERY_STRING', ''):
if six.PY3:
newurl += '?' + request.META['QUERY_STRING']
else:
# `query_string` is a bytestring. Appending it to the unicode
# string `newurl` will fail if it isn't ASCII-only. This isn't
# allowed; only broken software generates such query strings.
# Better drop the invalid query string than crash (#15152).
try:
newurl += '?' + request.META['QUERY_STRING'].decode()
except UnicodeDecodeError:
pass
return http.HttpResponsePermanentRedirect(newurl)
0
Example 32
@csrf_exempt
def csp_report(request, csp_save=False, csp_log=True):
"""
.. _csp_report:
Collect Content Security Policy reports from browsers. This view has
two optional keyword arguments:
``csp_save`` if True, reports will be saved as ``CspReport`` objects
in database; this table is registered with Django
Admin, so they can be later viewed in admin console.
``csp_log`` if True, reports will be logged through Django logging
facility under ``security`` class
By default only logging is enabled. To collect reports, this view needs to
be added to project's urls.py. Examples:
Default mode, only logger enable, no database logging:
``url(r'^csp-report/$', security.views.csp_report),``
Logger and database enabled:
``url(r'^csp-report/$', security.views.csp_report,
kwargs={'csp_save':True,'csp_log':True}),``
"""
# http://www.w3.org/TR/CSP/#sample-violation-report
if not request.method == 'POST':
log.debug('Unexpect CSP report method %s', request.method)
return HttpResponseForbidden()
if (
'CONTENT_TYPE' not in request.META
or request.META['CONTENT_TYPE'] != 'application/json'
):
log.debug('Missing CSP report Content-Type %s', request.META)
return HttpResponseForbidden()
try:
csp_dict = json.loads(request.body)
except ValueError:
log.debug('Cannot JSON decode CSP report %s', request.body)
return HttpResponseForbidden()
if 'csp-report' not in csp_dict:
log.debug('Invalid CSP report structure %s', csp_dict)
return HttpResponseForbidden()
report = csp_dict['csp-report']
reporting_ip = request.META['REMOTE_ADDR']
reporting_ua = request.META['HTTP_USER_AGENT']
# log message about received CSP violation to Django log
if csp_log:
log.warn(
'Content Security Policy violation: '
'%s, reporting IP %s, user agent %s',
report, reporting_ip, reporting_ua
)
# save received CSP violation to database
if csp_save:
csp_report = CspReport(
docuement_uri=report.get('docuement-uri'),
referrer=report.get('referrer'),
blocked_uri=report.get('blocked-uri'),
violated_directive=report.get('violated-directive'),
original_policy=report.get('original-policy'),
sender_ip=reporting_ip,
user_agent=reporting_ua,
)
csp_report.save()
# return 204 No Content to the client
# per http://www.w3.org/TR/CSP/#report-uri
# "Note: The user agent ignores the fetched resource"
resp = HttpResponse()
resp.status_code = 204
return resp
0
Example 33
Project: GAE-Bulk-Mailer Source File: common.py
def process_request(self, request):
"""
Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW
"""
# Check for denied User-Agents
if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
logger.warning('Forbidden (User agent): %s', request.path,
extra={
'status_code': 403,
'request': request
}
)
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
# Check for a redirect based on settings.APPEND_SLASH
# and settings.PREPEND_WWW
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.PREPEND_WWW and old_url[0] and
not old_url[0].startswith('www.')):
new_url[0] = 'www.' + old_url[0]
# Append a slash if APPEND_SLASH is set and the URL doesn't have a
# trailing slash and there is no pattern for the current path
if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
urlconf = getattr(request, 'urlconf', None)
if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST':
raise RuntimeError((""
"You called this URL via POST, but the URL doesn't end "
"in a slash and you have APPEND_SLASH set. Django can't "
"redirect to the slash URL while maintaining POST data. "
"Change your form to point to %s%s (note the trailing "
"slash), or set APPEND_SLASH=False in your Django "
"settings.") % (new_url[0], new_url[1]))
if new_url == old_url:
# No redirects required.
return
if new_url[0]:
newurl = "%s://%s%s" % (
request.is_secure() and 'https' or 'http',
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.META.get('QUERY_STRING', ''):
if six.PY3:
newurl += '?' + request.META['QUERY_STRING']
else:
# `query_string` is a bytestring. Appending it to the unicode
# string `newurl` will fail if it isn't ASCII-only. This isn't
# allowed; only broken software generates such query strings.
# Better drop the invalid query string than crash (#15152).
try:
newurl += '?' + request.META['QUERY_STRING'].decode()
except UnicodeDecodeError:
pass
return http.HttpResponsePermanentRedirect(newurl)
0
Example 34
Project: ska Source File: views.py
def login(request):
"""Login.
Authenticate with `ska` token into Django.
:param django.http.HttpRequest request:
:return django.http.HttpResponse:
"""
user = authenticate(request=request)
next_url = request.GET.get('next', None)
if not next_url:
if versions.DJANGO_GTE_1_7:
request_data = request.GET
else:
request_data = request.REQUEST
provider_data = get_provider_data(request_data)
if provider_data:
next_url = provider_data.get('REDIRECT_AFTER_LOGIN',
REDIRECT_AFTER_LOGIN)
if not next_url:
next_url = '/'
if user is not None:
auth_login(request, user)
name = user.first_name or user.username
messages.info(request, _("Login succeeded. Welcome, {0}.").format(name))
return HttpResponseRedirect(next_url)
else:
return HttpResponseForbidden(_("Authentication error!"))
0
Example 35
Project: django-frontendadmin Source File: views.py
def _get_instance(request, mode_name, app_label, model_name, instance_id=None,
form=None,
form_fields=None,
form_exclude=None):
'''
Returns the model and an instance_form for the given arguments. If an primary
key (instance_id) is given, it will return also the instance.
If the user has no permission to add, change or delete the object, a
HttpResponse is returned.
'''
# Check for permission to add/change/delete this object
if not check_permission(request, mode_name, app_label, model_name):
return HttpResponseForbidden('You have no permission to do this!')
try:
model = get_model(app_label, model_name)
# Model does not exist
except AttributeError:
return HttpResponseForbidden('This model does not exist!')
label = '%s.%s' % (app_label, model_name)
# get form for model
if label in FORMS and not form:
form = import_function(FORMS[label])
elif model in site._registry and not form:
form = site._registry[model].form
elif form is None:
form = FrontendAdminModelForm
if label in EXCLUDES:
form_exclude = EXCLUDES[label]
if label in FIELDS:
form_fields = FIELDS[label]
instance_form = modelform_factory(model, form=form,
fields=form_fields, exclude=form_exclude)
# if instance_id is set, grab this model object
if instance_id:
instance = model.objects.get(pk=instance_id)
return model, instance_form, instance
return model, instance_form
0
Example 36
Project: django-wakawaka Source File: views.py
def edit(request, slug, rev_id=None, template_name='wakawaka/edit.html',
extra_context=None, wiki_page_form=WikiPageForm,
wiki_delete_form=DeleteWikiPageForm):
"""
Displays the form for editing and deleting a page.
"""
if extra_context is None:
extra_context = {}
# Get the page for slug and get a specific revision, if given
try:
queryset = WikiPage.objects.all()
page = queryset.get(slug=slug)
rev = page.current
initial = {'content': page.current.content}
# Do not allow editing wiki pages if the user has no permission
if not request.user.has_perms(('wakawaka.change_wikipage', 'wakawaka.change_revision' )):
return HttpResponseForbidden(ugettext('You don\'t have permission to edit pages.'))
if rev_id:
# There is a specific revision, fetch this
rev_specific = Revision.objects.get(pk=rev_id)
if rev.pk != rev_specific.pk:
rev = rev_specific
rev.is_not_current = True
initial = {'content': rev.content, 'message': _('Reverted to "%s"' % rev.message)}
# This page does not exist, create a dummy page
# Note that it's not saved here
except WikiPage.DoesNotExist:
# Do not allow adding wiki pages if the user has no permission
if not request.user.has_perms(('wakawaka.add_wikipage', 'wakawaka.add_revision',)):
return HttpResponseForbidden(ugettext('You don\'t have permission to add wiki pages.'))
page = WikiPage(slug=slug)
page.is_initial = True
rev = None
initial = {'content': _('Describe your new page %s here...' % slug),
'message': _('Initial revision')}
# Don't display the delete form if the user has nor permission
delete_form = None
# The user has permission, then do
if request.user.has_perm('wakawaka.delete_wikipage') or \
request.user.has_perm('wakawaka.delete_revision'):
delete_form = wiki_delete_form(request)
if request.method == 'POST' and request.POST.get('delete'):
delete_form = wiki_delete_form(request, request.POST)
if delete_form.is_valid():
return delete_form.delete_wiki(request, page, rev)
# Page add/edit form
form = wiki_page_form(initial=initial)
if request.method == 'POST':
form = wiki_page_form(data=request.POST)
if form.is_valid():
# Check if the content is changed, except there is a rev_id and the
# user possibly only reverted the HEAD to it
if not rev_id and initial['content'] == form.cleaned_data['content']:
form.errors['content'] = (_('You have made no changes!'),)
# Save the form and redirect to the page view
else:
try:
# Check that the page already exist
queryset = WikiPage.objects.all()
page = queryset.get(slug=slug)
except WikiPage.DoesNotExist:
# Must be a new one, create that page
page = WikiPage(slug=slug)
page.save()
form.save(request, page)
kwargs = {
'slug': page.slug,
}
redirect_to = reverse('wakawaka_page', kwargs=kwargs)
messages.success(request, ugettext('Your changes to %s were saved' % page.slug))
return HttpResponseRedirect(redirect_to)
template_context = {
'form': form,
'delete_form': delete_form,
'page': page,
'rev': rev,
}
template_context.update(extra_context)
return render_to_response(template_name, template_context,
RequestContext(request))
0
Example 37
Project: dirigible-spreadsheet Source File: views_api_0_1.py
@rollback_on_exception
def calculate_and_get_json_for_api(request, username, sheet_id):
sheet = get_object_or_404(Sheet, pk=sheet_id, owner__username=username)
pads = None
if request.method == 'POST':
params = request.POST
else:
params = request.GET
if 'api_key' in params:
if not sheet.allow_json_api_access:
transaction.rollback()
return HttpResponseForbidden()
elif params['api_key'] != sheet.api_key:
transaction.rollback()
return HttpResponseForbidden()
elif 'dirigible_l337_private_key' in params:
pads = OneTimePad.objects.filter(
user=sheet.owner,
guid=params['dirigible_l337_private_key']
)
too_old = datetime.now() - timedelta(36000)
if len(pads) != 1 or pads[0].creation_time < too_old:
transaction.rollback()
return HttpResponseForbidden()
else:
transaction.rollback()
return HttpResponseForbidden()
worksheet = sheet.unjsonify_worksheet()
for encoded_loc, new_formula in params.items():
colrow = cell_ref_as_string_to_coordinates(encoded_loc)
if colrow is not None:
col, row = colrow
worksheet.set_cell_formula(col, row, new_formula)
sheet.jsonify_worksheet(worksheet)
try:
sheet.calculate()
worksheet = sheet.unjsonify_worksheet()
if worksheet._usercode_error:
return HttpResponse(json.dumps({
"usercode_error": {
"message": worksheet._usercode_error["message"],
"line": str(worksheet._usercode_error["line"])
}
}))
response = HttpResponse(
_sheet_to_value_only_json(sheet.name, worksheet))
response['Access-Control-Allow-Origin'] = '*'
return response
except (Exception, HTTPError), e:
return HttpResponse(str(e))
finally:
transaction.commit()
0
Example 38
Project: coursys Source File: views.py
@requires_course_by_slug
@transaction.atomic
def submit(request, course_slug):
person = get_object_or_404(Person,userid=request.user.username)
course = get_object_or_404(CourseOffering, slug = course_slug)
member = Member.objects.exclude(role='DROP').get(person=person, offering=course)
error_info=None
name = request.POST.get('GroupName')
if name:
name = name[:30]
#Check if group has a unique name
if Group.objects.filter(name=name,courseoffering=course):
error_info="A group named \"%s\" already exists" % (name)
messages.add_message(request, messages.ERROR, error_info)
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
#Check if the group name is empty, these two checks may need to be moved to forms later.
if name == "":
error_info = "Group name cannot be empty: please enter a group name."
messages.add_message(request, messages.ERROR, error_info)
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
else:
# find selected activities
selected_act = []
activities = Activity.objects.filter(offering=course, group=True, deleted=False)
if not is_course_staff_by_slug(request, course_slug):
activities = activities.exclude(status='INVI')
for activity in activities:
activityForm = ActivityForm(request.POST, prefix=activity.slug)
if activityForm.is_valid() and activityForm.cleaned_data['selected'] == True:
selected_act.append(activity)
# no selected activities: fail.
if not selected_act:
messages.add_message(request, messages.ERROR, "Group not created: no activities selected.")
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
#groupForSemesterForm = GroupForSemesterForm(request.POST)
#if groupForSemesterForm.is_valid():
# groupForSemester = groupForSemesterForm.cleaned_data['selected']
groupForSemester = False
#validate database integrity before saving anything.
#If one student is in a group for an activity, he/she cannot be in another group for the same activity.
if is_course_student_by_slug(request, course_slug):
isStudentCreatedGroup = True
studentList = []
studentList.append(member)
elif is_course_staff_by_slug(request, course_slug):
isStudentCreatedGroup = False
studentList = []
students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
for student in students:
studentForm = StudentForm(request.POST, prefix = student.person.userid)
if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
studentList.append(student)
#Check if students has already in a group
if _validateIntegrity(request,isStudentCreatedGroup, groupForSemester, course, studentList, selected_act) == False:
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
#No selected members,group creating will fail.
if not studentList:
messages.add_message(request, messages.ERROR, "Group not created: no members selected.")
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
group = Group(name=name, manager=member, courseoffering=course, groupForSemester = groupForSemester)
group.save()
#LOG EVENT#
l = LogEntry(userid=request.user.username,
description="created a new group %s for %s." % (group.name, course),
related_object=group )
l.save()
if is_course_student_by_slug(request, course_slug):
for activity in selected_act:
groupMember = GroupMember(group=group, student=member, confirmed=True, activity_id=activity.id)
groupMember.save()
#LOG EVENT#
l = LogEntry(userid=request.user.username,
description="automatically became a group member of %s for activity %s." % (group.name, groupMember.activity),
related_object=groupMember )
l.save()
messages.add_message(request, messages.SUCCESS, 'Group Created')
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
elif is_course_staff_by_slug(request, course_slug):
students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
for student in students:
studentForm = StudentForm(request.POST, prefix = student.person.userid)
if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
for activity in selected_act:
groupMember = GroupMember(group=group, student=student, confirmed=True, activity_id=activity.id)
groupMember.save()
#LOG EVENT#
l = LogEntry(userid=request.user.username,
description="added %s as a group member to %s for activity %s." % (student.person.userid,group.name, groupMember.activity),
related_object=groupMember )
l.save()
n = NewsItem(user=student.person, author=member.person, course=group.courseoffering,
source_app="group", title="Added to Group",
content="You have been added the group %s." % (group.name),
url=reverse('groups.views.groupmanage', kwargs={'course_slug':course.slug})
)
n.save()
messages.add_message(request, messages.SUCCESS, 'Group Created')
return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
else:
return HttpResponseForbidden()
0
Example 39
Project: fileshackproject Source File: views.py
@require_store
@require_login
def iframe(request, store):
if request.method != "POST":
t = loader.get_template("fileshack/iframe.html")
c = RequestContext(request)
return HttpResponse(t.render(c))
if not request.FILES.has_key("file"):
return HttpResponseForbidden()
f = request.FILES["file"]
item = Item()
item.fileobject.name = urllib.unquote(f.name)
item.store = store
item.size = f.size
item.size_total = f.size
if store.item_limit and f.size > store.item_limit*1024*1024:
return HttpResponse(JSONEncoder().encode({
"status": "itemlimitreached",
"error_label": "Upload failed",
"error_message": "Item size is limited to %d MB" % store.item_limit,
"item": item.simple(),
}))
if store.store_limit and store.total() + f.size > store.store_limit*1024*1024:
return HttpResponse(JSONEncoder().encode({
"status": "storelimitreached",
"error_label": "Upload failed",
"error_message": "The store size limit of %d MB has been reached" % store.store_limit,
"item": item.simple(),
}))
item.fileobject.save(urllib.unquote(f.name), f)
item.save()
return HttpResponse(JSONEncoder().encode({
"status": "success",
"item": Item.objects.get(pk=item.pk).simple()
}))
0
Example 40
Project: coursys Source File: views.py
@login_required
@transaction.atomic
def remove_student(request, course_slug, group_slug):
course = get_object_or_404(CourseOffering, slug = course_slug)
group = get_object_or_404(Group, courseoffering = course, slug = group_slug)
members = GroupMember.objects.filter(group = group).select_related('group', 'student', 'student__person', 'activity')
# check permissions
if is_course_staff_by_slug(request, course_slug):
is_staff = True
elif is_course_student_by_slug(request, course_slug):
is_staff = False
memberships = [m for m in members if m.student.person.userid == request.user.username]
if not memberships:
# student must be in this group
return HttpResponseForbidden()
else:
return HttpResponseForbidden()
if request.method == "POST":
for m in members:
f = StudentForm(request.POST, prefix=unicode(m.student.person.userid_or_emplid()) + '_' + m.activity.slug)
if (is_staff or m.student_editable(request.user.username)=="") \
and f.is_valid() and f.cleaned_data['selected'] == True:
m.delete()
#LOG EVENT#
l = LogEntry(userid=request.user.username,
description="deleted %s in group %s for %s." % (m.student.person.userid, group.name, m.activity),
related_object=m.group)
l.save()
if is_staff:
return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
else:
return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
else:
data = []
for m in members:
editable = m.student_editable(request.user.username)
if is_staff or editable == "":
f = StudentForm(prefix=unicode(m.student.person.userid_or_emplid()) + '_' + m.activity.slug)
data.append({'form': f, 'member': m})
else:
data.append({'form': None, 'member': m, 'reason': editable})
return render_to_response('groups/remove_student.html', \
{'course':course, 'group' : group, 'data':data, 'is_staff':is_staff}, \
context_instance = RequestContext(request))
0
Example 41
Project: junction Source File: votes_views.py
@login_required
def proposal_vote(request, conference_slug, proposal_slug, up_vote):
conference = get_object_or_404(Conference, slug=conference_slug)
public_voting = ConferenceSettingConstants.ALLOW_PUBLIC_VOTING_ON_PROPOSALS
public_voting_setting = conference.conferencesetting_set.filter(name=public_voting['name']).first()
if public_voting_setting and not public_voting_setting.value:
return HttpResponseForbidden()
proposal = get_object_or_404(Proposal, slug=proposal_slug, conference=conference)
if not permissions.is_proposal_voting_allowed(proposal):
return HttpResponseForbidden()
if up_vote is None:
# Remove any vote casted and return
ProposalVote.objects.filter(proposal=proposal, voter=request.user).delete()
return HttpResponse(proposal.get_votes_count())
proposal_vote, created = ProposalVote.objects.get_or_create(
proposal=proposal, voter=request.user) # @UnusedVariable
if permissions.is_proposal_reviewer(request.user, conference):
role = ProposalUserVoteRole.REVIEWER
else:
role = ProposalUserVoteRole.PUBLIC
proposal_vote.role = role
proposal_vote.up_vote = up_vote
proposal_vote.save()
return HttpResponse(proposal.get_votes_count())
0
Example 42
Project: baruwa Source File: views.py
def filemanager(request, user_id, domain_id=None):
"handle file access requests from jquery"
def unauthorized():
"return unauthorized"
body = anyjson.dumps(dict(success=False, error=_("Not authorized.")))
return HttpResponseForbidden(body, mimetype='application/json')
if request.user.is_authenticated():
user = User.objects.get(pk=user_id)
if user:
if not check_access(request, user):
unauthorized()
action = request.REQUEST.get('action', None)
if domain_id:
requesturl = reverse('domains-image-manager',
args=[domain_id, user_id])
else:
requesturl = reverse('accounts-image-manager',
args=[user_id])
if action and action == 'auth':
body = dict(success=True, data=dict(
move=dict(enabled=False, handler=requesturl),
rename=dict(enabled=False, handler=requesturl),
remove=dict(enabled=True, handler=requesturl),
mkdir=dict(enabled=False, handler=requesturl),
upload=dict(enabled=True, handler=requesturl + '?action=upload',
accept_ext=['gif', 'jpg', 'png']),
baseUrl='')
)
elif action and action == 'list':
imgquery = SignatureImg.objects.filter(owner=user)
imgs = {}
def builddict(img):
imgs[img.name] = reverse('img-view', args=[user_id, img.id])
[builddict(img) for img in imgquery]
body = dict(success=True, data=dict(
directories={},
files=imgs))
elif action and action == 'upload':
if request.method == 'POST':
handle = request.FILES['handle']
prevent = False
currentsigs = SignatureImg.objects.filter(owner=user).count()
profile = UserProfile.objects.filter(user=user)[0]
if user.is_superuser:
prevent = True
elif profile.account_type == 2:
domains = UserAddresses.objects.filter(address_type=1, user=user).count()
if currentsigs >= domains:
prevent = True
else:
if currentsigs:
prevent = True
if not prevent:
chunk = handle.read()
ext = imghdr.what('./xxx', chunk)
if ext in ['gif', 'jpg', 'png', 'jpeg']:
try:
name = request.REQUEST.get('newName') or 'image.%s' % ext
name = os.path.basename(name)
dbimg = SignatureImg(
name = name,
image = base64.encodestring(chunk),
content_type = handle.content_type,
owner = user,)
dbimg.save()
respond = _('File has been uploaded')
except DatabaseError:
respond = _('An error occured, try again later')
else:
respond = _('The uploaded file is not acceptable')
chunk = None
handle.close()
else:
respond = _('You already have a signature image, '
'delete the current image before '
'uploading a new one')
return HttpResponse(respond)
elif action and action == 'remove':
try:
fname = request.REQUEST.get('file', None)
SignatureImg.objects.filter(owner=user, name=fname).delete()
respond = _('The file has been deleted')
success = True
except DatabaseError:
respond = _('The file could not be deleted')
success = False
body = dict(success=success, data=respond)
else:
body = dict(success=False, error=_("Action not supported"),
errorno=255)
return HttpResponse(anyjson.dumps(body), mimetype='application/json')
else:
unauthorized()
0
Example 43
Project: django-twilio Source File: decorators.py
def twilio_view(f):
"""
This decorator provides several helpful shortcuts for writing Twilio views.
- It ensures that only requests from Twilio are passed through. This
helps protect you from forged requests.
- It ensures your view is exempt from CSRF checks via Django's
@csrf_exempt decorator. This is necessary for any view that accepts
POST requests from outside the local domain (eg: Twilio's servers).
- It enforces the blacklist. If you've got any ``Caller``s who are
blacklisted, any requests from them will be rejected.
- It allows your view to (optionally) return TwiML to pass back to
Twilio's servers instead of building an ``HttpResponse`` object
manually.
- It allows your view to (optionally) return any ``twilio.Verb`` object
instead of building a ``HttpResponse`` object manually.
.. note::
The forgery protection checks ONLY happen if ``settings.DEBUG =
False`` (aka, your site is in production).
Usage::
from twilio import twiml
@twilio_view
def my_view(request):
r = twiml.Response()
r.message('Thanks for the SMS message!')
return r
"""
@csrf_exempt
@wraps(f)
def decorator(request_or_self, *args, **kwargs):
class_based_view = not isinstance(request_or_self, HttpRequest)
if not class_based_view:
request = request_or_self
else:
assert len(args) >= 1
request = args[0]
# Turn off Twilio authentication when explicitly requested, or
# in debug mode. Otherwise things do not work properly. For
# more information, see the docs.
use_forgery_protection = getattr(
settings,
'DJANGO_TWILIO_FORGERY_PROTECTION',
not settings.DEBUG,
)
if use_forgery_protection:
if request.method not in ['GET', 'POST']:
return HttpResponseNotAllowed(request.method)
# Forgery check
try:
validator = RequestValidator(TWILIO_AUTH_TOKEN)
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError):
return HttpResponseForbidden()
if request.method == 'POST':
if not validator.validate(url, request.POST, signature):
return HttpResponseForbidden()
if request.method == 'GET':
if not validator.validate(url, request.GET, signature):
return HttpResponseForbidden()
# Blacklist check, by default is true
check_blacklist = getattr(
settings,
'DJANGO_TWILIO_BLACKLIST_CHECK',
True
)
if check_blacklist:
blacklisted_resp = get_blacklisted_response(request)
if blacklisted_resp:
return blacklisted_resp
response = f(request_or_self, *args, **kwargs)
if isinstance(response, (text_type, bytes)):
return HttpResponse(response, content_type='application/xml')
elif isinstance(response, Verb):
return HttpResponse(str(response), content_type='application/xml')
else:
return response
return decorator
0
Example 44
Project: vumi-go Source File: views.py
@login_required
def user_detail(request, user_id=None):
"""Shows a form that allows you to edit the details of this user"""
# Is the `user` an admin, do they have the rights to edit a user?
user_profile = request.user.get_profile()
if not user_profile.is_admin:
return HttpResponseForbidden("You're not an admin.")
# Are they editing a member of the same organisation?
if user_id:
# editing
edit_user = get_object_or_404(User, id=user_id)
edit_user_profile = edit_user.get_profile()
if user_profile.organisation != edit_user_profile.organisation:
return HttpResponseForbidden("This user is not in your \
organisation.")
else:
# creating a new user
edit_user = None
edit_user_profile = UserProfile(
organisation=user_profile.organisation)
user_form = UserAccountForm(instance=edit_user)
user_profile_form = UserProfileForm(instance=edit_user_profile,
initial={
'organisation': user_profile.organisation
})
if request.method == 'POST':
user_form = UserAccountForm(request.POST, instance=edit_user)
user_profile_form = UserProfileForm(request.POST,
instance=edit_user_profile)
if user_form.is_valid() and user_profile_form.is_valid():
user_form.save()
user_profile_form.save()
messages.add_message(request, messages.INFO, 'User saved')
return render(request, 'account/user_detail.html', {
'edit_user': edit_user,
'user_form': user_form,
'user_profile_form': user_profile_form
})
0
Example 45
Project: doac Source File: decorators.py
def scope_required(*scopes):
"""
Test for specific scopes that the access token has been authenticated for before
processing the request and eventual response.
The scopes that are passed in determine how the decorator will respond to incoming
requests:
- If no scopes are passed in the arguments, the decorator will test for any available
scopes and determine the response based on that.
- If specific scopes are passed, the access token will be checked to make sure it has
all of the scopes that were requested.
This decorator will change the response if the access toke does not have the scope:
- If an invalid scope is requested (one that does not exist), all requests will be
denied, as no access tokens will be able to fulfill the scope request and the
request will be denied.
- If the access token does not have one of the requested scopes, the request will be
denied and the user will be returned one of two responses:
- A 400 response (Bad Request) will be returned if an unauthenticated user tries to
access the resource.
- A 403 response (Forbidden) will be returned if an authenticated user ties to access
the resource but does not have the correct scope.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from .exceptions.base import InvalidRequest, InsufficientScope
from .models import Scope
from .utils import request_error_header
try:
if not hasattr(request, "access_token"):
raise CredentialsNotProvided()
access_token = request.access_token
for scope_name in scopes:
try:
scope = access_token.scope.for_short_name(scope_name)
except Scope.DoesNotExist:
raise ScopeNotEnough()
except InvalidRequest as e:
response = HttpResponseBadRequest()
response["WWW-Authenticate"] = request_error_header(e)
return response
except InsufficientScope as e:
response = HttpResponseForbidden()
response["WWW-Authenticate"] = request_error_header(e)
return response
return view_func(request, *args, **kwargs)
return _wrapped_view
if scopes and hasattr(scopes[0], "__call__"):
func = scopes[0]
scopes = scopes[1:]
return decorator(func)
return decorator
0
Example 46
def edit(request, pk, modelform_class=BlockForm, permission_check=None, template_name='mezzanine_blocks/edit.html', success_url=None):
"""
This view provides a simple editor implementation for flatblocks.
There are two customization hooks. First of all you can specify your own
ModelForm class by passing it to the view using the ``modelform_class``
keyword-argument.
The other entry point helps you check permissions: Pass a simple function
via the ``permission_check`` keyword-argument in order to check
permissions on the flatblock-level::
def my_perm_check(request, block):
return request.user.is_staff
# ...
urlpatterns('blocks.views',
url('blocks/(?P<pk>\d+)/edit/$', 'edit',
kwargs={'permission_check': my_perm_check}),
)
The contract here is pretty simple: If the function returns False, the
view will return HttpResponseForbidden. Otherwise it will pass. So if you
want to do some fancy redirects if the permissions are wrong, return your
own HttpResponse-object/-subclass.
If everything is alright with the permissions, simply return True.
"""
flatblock = get_object_or_404(Block, pk=pk)
if permission_check is not None:
permcheck_result = permission_check(request, flatblock)
if permcheck_result is False:
return HttpResponseForbidden(_('You are not allowed to edit this block'))
if isinstance(permcheck_result, HttpResponse):
return permcheck_result
session_key = 'block.origin.%d' % (int(pk), )
if request.method == 'POST':
origin = request.session.get(session_key,
request.META.get('HTTP_REFERER', '/'))
form = modelform_class(request.POST, instance=flatblock)
if form.is_valid():
instance = form.save(commit=False)
instance.slug = flatblock.slug
instance.save()
del request.session[session_key]
redirect_to = success_url and success_url or origin
return HttpResponseRedirect(redirect_to)
else:
origin = request.META.get('HTTP_REFERER', '/')
# Don't set origin to this view's url no matter what
origin = origin == request.get_full_path() and request.session.get(session_key, '/') or origin
form = modelform_class(instance=flatblock)
request.session[session_key] = origin
return render_to_response(template_name, {
'form': form,
'origin': origin,
'flatblock': flatblock,
}, context_instance=RequestContext(request))
0
Example 47
Project: talk.org Source File: common.py
def process_request(self, request):
"""
Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW
"""
# Check for denied User-Agents
if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
# Check for a redirect based on settings.APPEND_SLASH
# and settings.PREPEND_WWW
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.PREPEND_WWW and old_url[0] and
not old_url[0].startswith('www.')):
new_url[0] = 'www.' + old_url[0]
# Append a slash if APPEND_SLASH is set and the URL doesn't have a
# trailing slash and there is no pattern for the current path
if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
try:
urlresolvers.resolve(request.path)
except urlresolvers.Resolver404:
new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST':
raise RuntimeError, (""
"You called this URL via POST, but the URL doesn't end "
"in a slash and you have APPEND_SLASH set. Django can't "
"redirect to the slash URL while maintaining POST data. "
"Change your form to point to %s%s (note the trailing "
"slash), or set APPEND_SLASH=False in your Django "
"settings.") % (new_url[0], new_url[1])
if new_url != old_url:
# Redirect if the target url exists
try:
urlresolvers.resolve(new_url[1])
except urlresolvers.Resolver404:
pass
else:
if new_url[0]:
newurl = "%s://%s%s" % (
request.is_secure() and 'https' or 'http',
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.GET:
newurl += '?' + request.GET.urlencode()
return http.HttpResponsePermanentRedirect(newurl)
return None
0
Example 48
def post(self, request, *args, **kwargs):
content_type = get_object_or_404(ContentType, pk=self.kwargs.get("content_type_id"))
try:
obj = content_type.get_object_for_this_type(pk=self.kwargs.get("object_id"))
except ObjectDoesNotExist:
raise Http404("Object not found.")
if not request.user.has_perm("likes.can_like", obj):
return HttpResponseForbidden()
like, liked = Like.like(request.user, content_type, obj.id)
if liked:
object_liked.send(sender=Like, like=like, request=request)
else:
object_unliked.send(sender=Like, object=obj, request=request)
if request.is_ajax():
html_ctx = widget_context(request.user, obj)
template = "pinax/likes/_widget.html"
if request.GET.get("t") == "b":
template = "pinax/likes/_widget_brief.html"
data = {
"html": render_to_string(
template,
context=html_ctx,
request=request
),
"likes_count": html_ctx["like_count"],
"liked": html_ctx["liked"],
}
return JsonResponse(data)
return HttpResponseRedirect(request.META.get("HTTP_REFERER", "/"))
0
Example 49
def get(self, request):
"""
Process the GET content request.
:param request: The WSGI request object.
:type request: django.core.handlers.wsgi.WSGIRequest
:return: An appropriate HTTP reply
:rtype: django.http.HttpResponse
"""
host = request.get_host()
path = os.path.realpath(request.path_info)
# Check authorization if http isn't being used. This environ variable must
# be available in all implementations so it is not dependant on Apache httpd:
# https://www.python.org/dev/peps/pep-0333/#environ-variables
if request.environ['wsgi.url_scheme'] != 'http':
if not allow_access(request.environ, host):
# Not Authorized
logger.info(_('Denying {host} access to {path} because one or more'
' authenticators failed.').format(host=host, path=path))
return HttpResponseForbidden()
if not any([path.startswith(prefix) for prefix in self.safe_serving_paths]):
# Someone is requesting something they shouldn't.
logger.info(_('Denying {host} request to {path} as it does not resolve to'
'a Pulp content path.').format(host=host, path=path))
return HttpResponseForbidden()
# Immediately 404 if the symbolic link doesn't even exist
if not os.path.lexists(request.path_info):
logger.debug(_('Symbolic link to {path} does not exist.').format(path=path))
raise Http404
if os.path.isdir(path):
logger.debug(_('Rendering directory index for {path}.').format(path=path))
return self.directory_index(path)
# Already downloaded
if os.path.exists(path):
logger.debug(_('Serving {path} with mod_xsendfile.').format(path=path))
return self.x_send(path)
logger.debug(_('Redirecting request for {path}.').format(path=path))
return self.redirect(request, self.key)
0
Example 50
Project: rpc4django Source File: views.py
@csrf_exempt
def serve_rpc_request(request):
'''
Handles rpc calls based on the content type of the request or
returns the method docuementation page if the request
was a GET.
**Parameters**
``request``
the Django HttpRequest object
'''
if request.method == "POST" and int(request.META.get('CONTENT_LENGTH', 0)) > 0:
# Handle POST request with RPC payload
if LOG_REQUESTS_RESPONSES:
logger.debug('Incoming request: %s' % str(get_request_body(request)))
if is_xmlrpc_request(request):
if RESTRICT_XML:
raise Http404
if not check_request_permission(request, 'xml'):
return HttpResponseForbidden()
resp = dispatcher.xmldispatch(get_request_body(request),
request=request)
response_type = 'text/xml'
else:
if RESTRICT_JSON:
raise Http404
if not check_request_permission(request, 'json'):
return HttpResponseForbidden()
resp = dispatcher.jsondispatch(get_request_body(request),
request=request)
response_type = 'application/json'
if LOG_REQUESTS_RESPONSES:
logger.debug('Outgoing %s response: %s' % (response_type, resp))
return HttpResponse(resp, response_type)
elif request.method == 'OPTIONS':
# Handle OPTIONS request for "preflighted" requests
# see https://developer.mozilla.org/en/HTTP_access_control
response = HttpResponse('', 'text/plain')
origin = request.META.get('HTTP_ORIGIN', 'unknown origin')
response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
response['Access-Control-Max-Age'] = 0
response['Access-Control-Allow-Credentials'] = \
str(HTTP_ACCESS_CREDENTIALS).lower()
response['Access-Control-Allow-Origin'] = HTTP_ACCESS_ALLOW_ORIGIN
response['Access-Control-Allow-Headers'] = \
request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', '')
if LOG_REQUESTS_RESPONSES:
logger.debug('Outgoing HTTP access response to: %s' % (origin))
return response
else:
# Handle GET request
if RESTRICT_METHOD_SUMMARY:
# hide the docuementation by raising 404
raise Http404
# show docuementation
methods = dispatcher.list_methods()
template_data = {
'methods': methods,
'url': URL,
# rpc4django version
'version': version(),
# restricts the ability to test the rpc server from the docs
'restrict_rpctest': RESTRICT_RPCTEST,
}
from django.template import RequestContext
return render_to_response('rpc4django/rpcmethod_summary.html',
template_data,
context_instance=RequestContext(request))