我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.http.HttpResponseForbidden()。
def _org_lock_unlock(request, org_id, action): org = get_object_or_404(Org, id=org_id) if org.scratch: raise HttpResponseForbidden('Scratch orgs may not be locked/unlocked') if action == 'lock': form_class = OrgLockForm template = 'cumulusci/org_lock.html' elif action == 'unlock': form_class = OrgUnlockForm template = 'cumulusci/org_unlock.html' if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): if request.POST['action'] == 'Lock': org.lock() elif request.POST['action'] == 'Unlock': org.unlock() return HttpResponseRedirect(org.get_absolute_url()) else: form = form_class() return render(request, template, context={'form': form, 'org': org})
def _delete_notification(request, notification): if request.user != notification.user: return HttpResponseForbidden() if request.method == 'POST': form = DeleteNotificationForm(request.POST) if form.is_valid(): if request.POST['action'] == 'Delete': notification.delete() return HttpResponseRedirect('/notifications') else: form = DeleteNotificationForm() return render( request, 'notification/delete_notification.html', context={ 'form': form, 'notification': notification, 'notification_type': notification.__class__.__name__.replace( 'Notification', '', ), }, )
def build_rebuild(request, build_id): build = get_object_or_404(Build, id=build_id) if not request.user.is_staff: return HttpResponseForbidden( 'You are not authorized to rebuild builds') rebuild = Rebuild( build=build, user=request.user, status='queued', ) rebuild.save() if not build.log: build.log = '' build.log += '\n=== Build restarted at {} by {} ===\n'.format( timezone.now(), request.user.username) build.current_rebuild = rebuild build.save() return HttpResponseRedirect('/builds/{}'.format(build.id))
def anuncioPorBusca(request): form = formBusca(request.GET) anuncios = getAnunciosPorSubstring(request.GET.get('t')) edit_forms = getFormsEdicaoDeAnuncios(anuncios) return render(request, 'anuncios/anuncios.html', {'anuncios': anuncios, 'formBusca':form, 'localidade':"Localidade ", 'editforms':edit_forms}) ################################################################################################### #View que renderiza anuncios do banco de dados filtrados pelo usuario que os criou # #Nome: anuncioPorUsuario #Autor: Renan Basilio #Versao: 1.0 # #Algoritmo: # 1. Verifica se o usuario esta autenticado # 2. Se nao retorna uma HttpResponseForbidden # 3. Se sim, inicializa form de busca e constroi lista de anuncios a partir do metodo getAnunciosPorUsuario # 4. Chama o metodo render # ####################################################################################################
def permission_denied(request, exception, template_name='403.html'): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
def box_edit(request, label): if not load_can_edit()(request, **get_auth_vars(request)): return HttpResponseForbidden() next = request.GET.get("next") try: box = Box.objects.get(label=label) except Box.DoesNotExist: box = None form = BoxForm(request.POST, instance=box, prefix=label) if form.is_valid(): if box is None: box = form.save(commit=False) box.label = label box.created_by = request.user box.last_updated_by = request.user box.save() else: form.save() return redirect(next)
def proposal_cancel(request, pk): queryset = ProposalBase.objects.select_related("speaker") proposal = get_object_or_404(queryset, pk=pk) proposal = ProposalBase.objects.get_subclass(pk=proposal.pk) if proposal.speaker.user != request.user: return HttpResponseForbidden() if request.method == "POST": proposal.cancelled = True proposal.save() # @@@ fire off email to submitter and other speakers messages.success(request, "%s has been cancelled" % proposal.title) return redirect("dashboard") return render(request, "proposals/proposal_cancel.html", { "proposal": proposal, })
def proposal_leave(request, pk): queryset = ProposalBase.objects.select_related("speaker") proposal = get_object_or_404(queryset, pk=pk) proposal = ProposalBase.objects.get_subclass(pk=proposal.pk) try: speaker = proposal.additional_speakers.get(user=request.user) except ObjectDoesNotExist: return HttpResponseForbidden() if request.method == "POST": proposal.additional_speakers.remove(speaker) # @@@ fire off email to submitter and other speakers messages.success(request, "You are no longer speaking on %s" % proposal.title) return redirect("dashboard") ctx = { "proposal": proposal, } return render(request, "proposals/proposal_leave.html", ctx)
def document_create(request, proposal_pk): queryset = ProposalBase.objects.select_related("speaker") proposal = get_object_or_404(queryset, pk=proposal_pk) proposal = ProposalBase.objects.get_subclass(pk=proposal.pk) if proposal.cancelled: return HttpResponseForbidden() if request.method == "POST": form = SupportingDocumentCreateForm(request.POST, request.FILES) if form.is_valid(): document = form.save(commit=False) document.proposal = proposal document.uploaded_by = request.user document.save() return redirect("proposal_detail", proposal.pk) else: form = SupportingDocumentCreateForm() return render(request, "proposals/document_create.html", { "proposal": proposal, "form": form, })
def begin(request): sso = discourse_sso.DiscourseSigner(settings.DISCOURSE_SSO_SECRET) raw_payload = request.GET.get('sso', '') raw_signature = request.GET.get('sig', '') try: payload = sso.unsign(raw_payload, raw_signature) except discourse_sso.SignatureError: return HttpResponseForbidden() if b'return_sso_url' not in payload: return HttpResponseForbidden() out_payload, out_signature = sso.sign( utils.make_payload(request.user, payload[b'nonce'])) redirect_to = '{}?{}'.format( payload[b'return_sso_url'].decode('utf8'), urllib.parse.urlencode({ 'sso': out_payload, 'sig': out_signature})) return redirect(redirect_to)
def switch_team(request, target_username): other_user = User.objects.get(username=target_username) # The rules: # Superuser can switch to any team. access_ok = request.user.is_superuser # Users can switch to teams they are members of. if not access_ok and other_user.id == request.user.id: access_ok = True # Users can switch to their own teams. if not access_ok: for membership in request.user.member_set.all(): if membership.team.user.id == other_user.id: access_ok = True break if not access_ok: return HttpResponseForbidden() request.user.profile.current_team = other_user.profile request.user.profile.save() return redirect("hc-checks")
def allowed_roles(allowed_roles_list): """ Decorator for views that checks that the user has permission to access the view function. If the user's role (request.session["course_roles"][course_id], set by SGAMiddleware) is in allowed_roles_list, the view_function is called, otherwise it returns a 403 response. """ def decorator(view_func): """ Decorator """ @wraps(view_func) def _wrapped_view(request, course_id, *args, **kwargs): """ Wrapped function """ role = request.session.get("course_roles", {}).get(course_id) if role in allowed_roles_list: request.role = role request.course = Course.objects.get(id=course_id) return view_func(request, course_id, *args, **kwargs) return HttpResponseForbidden() return _wrapped_view return decorator
def edit_timeline(request, slug, template_name="package/timeline_form.html"): project = get_object_or_404(Project, slug=slug) if not request.user.profile.can_edit_package(project): return HttpResponseForbidden("permission denied") if request.POST: formset = TimelineEventFormSet(data=request.POST, project=project,) else: formset = TimelineEventFormSet(project=project, queryset=TimelineEvent.objects.filter(project=project)) if formset.is_valid(): formset.save() messages.add_message(request, messages.INFO, 'Project updated successfully') return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug})) return render(request, template_name, { "formset": formset, "package": project, "action": "Save", })
def edit_images(request, slug, template_name="package/images_form.html"): project = get_object_or_404(Project, slug=slug) if not request.user.profile.can_edit_package(project): return HttpResponseForbidden("permission denied") if request.POST: formset = ProjectImagesFormSet(data=request.POST, files=request.FILES, project=project,) else: formset = ProjectImagesFormSet(project=project, queryset=ProjectImage.objects.filter(project=project)) if formset.is_valid(): formset.save() messages.add_message(request, messages.INFO, 'Project updated successfully') return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug})) return render(request, template_name, { "formset": formset, "package": project, "action": "Save", })
def add_grid(request, template_name="grid/update_grid.html"): """Creates a new grid, requires user to be logged in. Works for both GET and POST request methods Template context: * ``form`` - an instance of :class:`~app.grid.forms.GridForm` """ if not request.user.profile.can_add_grid: return HttpResponseForbidden("permission denied") new_grid = Grid() form = GridForm(request.POST or None, instance=new_grid) if form.is_valid(): new_grid = form.save() return HttpResponseRedirect(reverse('grid', kwargs={'slug': new_grid.slug})) return render(request, template_name, {'form': form})
def edit_grid(request, slug, template_name="grid/update_grid.html"): """View to modify the grid, handles GET and POST requests. This view requires user to be logged in. Template context: * ``form`` - instance of :class:`grid.forms.GridForm` """ if not request.user.profile.can_edit_grid: return HttpResponseForbidden("permission denied") grid = get_object_or_404(Grid, slug=slug) form = GridForm(request.POST or None, instance=grid) if form.is_valid(): grid = form.save() message = "Grid has been edited" messages.add_message(request, messages.INFO, message) return HttpResponseRedirect(reverse('grid', kwargs={'slug': grid.slug})) return render(request, template_name, {'form': form, 'grid': grid})
def add_feature(request, grid_slug, template_name="grid/update_feature.html"): """Adds a feature to the grid, accepts GET and POST requests. Requires user to be logged in Template context: * ``form`` - instance of :class:`grid.forms.FeatureForm` form * ``grid`` - instance of :class:`grid.models.Grid` model """ if not request.user.profile.can_add_grid_feature: return HttpResponseForbidden("permission denied") grid = get_object_or_404(Grid, slug=grid_slug) form = FeatureForm(request.POST or None) if form.is_valid(): feature = form.save(commit=False) feature.grid = grid feature.save() return HttpResponseRedirect(reverse('grid', kwargs={'slug': feature.grid.slug})) return render(request, template_name, {'form': form, 'grid': grid})
def edit_feature(request, id, template_name="grid/update_feature.html"): """edits feature on a grid - this view has the same semantics as :func:`grid.views.add_feature`. Requires the user to be logged in. """ if not request.user.profile.can_edit_grid_feature: return HttpResponseForbidden("permission denied") feature = get_object_or_404(Feature, id=id) form = FeatureForm(request.POST or None, instance=feature) if form.is_valid(): feature = form.save() return HttpResponseRedirect(reverse('grid', kwargs={'slug': feature.grid.slug})) return render(request, template_name, {'form': form, 'grid': feature.grid})
def add_new_grid_package(request, grid_slug, template_name="package/package_form.html"): """Add a package to a grid that isn't yet represented on the site.""" if not request.user.profile.can_add_grid_package: return HttpResponseForbidden("permission denied") grid = get_object_or_404(Grid, slug=grid_slug) new_package = Project() form = PackageForm(request.POST or None, instance=new_package) if form.is_valid(): new_package = form.save() GridPackage.objects.create( grid=grid, package=new_package ) return HttpResponseRedirect(reverse("grid", kwargs={"slug": grid_slug})) return render(request, template_name, {"form": form, "repo_data": repo_data_for_js(), "action": "add"})
def accept_or_deny(request): if request.user.usertype: return HttpResponseForbidden() else: op = request.GET.get('op') try: opk = int(request.GET.get('opk')) b = request.user.business o = Order.objects.get(pk=opk, food__business=b) except: return HttpResponseNotFound(NOTFOUNDMESSAGE) if op == 'accept': o.is_accept = True o.save() elif op == 'deny': o.delete() return HttpResponseRedirect(reverse('businessucenterindex'))
def post(self, request): if request.user.is_active: return HttpResponseForbidden() authapply_form = BusinessApplyForm(data=request.POST) if authapply_form.is_valid(): try: newauthapply = authapply_form.save(commit=False) newauthapply.user = request.user newauthapply.save() newauthapply.user.phonenumber = authapply_form.cleaned_data['phonenumber'] newauthapply.user.save() return render(request, 'auth/auth.html', { 'success': "???????????" }) except: return render(request, 'auth/auth.html', { 'error': "???????" }) else: return render(request, 'auth/auth.html', { 'form': authapply_form, })
def topicPage(request, topic_title): try: topic = Topic.getTopic(topic_title) except Topic.DoesNotExist: raise Http404() # edit topic form if request.method == 'POST': if not request.user.is_superuser: return HttpResponseForbidden() form = TopicForm(request.POST, instance=topic) if form.is_valid(): form.save() return redirect('topicPage', topic.urlTitle) showForm = True else: form = TopicForm(instance=topic) showForm = False threads = Thread.objects.filter(topic=topic) context = dict(topic=topic, threads=threads, showCreatedBy=True, showTopic=False, topicForm=form, showForm=showForm) return render(request, 'djeddit/topic.html', context)
def replyPost(request, post_uid=''): try: repliedPost = Post.objects.get(uid=post_uid) thread = repliedPost.thread except (Post.DoesNotExist, Thread.DoesNotExist): raise Http404 if thread.locked: return HttpResponseForbidden() repliedUser = repliedPost.created_by.username if repliedPost.created_by else 'guest' if request.method == 'POST': postForm = PostForm(request.POST) if postForm.is_valid(): post = postForm.save(commit=False) post.parent = repliedPost if request.user.is_authenticated(): post.created_by = request.user post.save() repliedPost.children.add(post) return HttpResponseRedirect(thread.relativeUrl) else: postForm = PostForm() postForm.fields['content'].label = '' context = dict(postForm=postForm, thread_id=thread.id, post_uid=post_uid, repliedUser=repliedUser) return render(request, 'djeddit/reply_form.html', context)
def editPost(request, post_uid=''): try: post = Post.objects.get(uid=post_uid) thread = post.thread except (Post.DoesNotExist, Thread.DoesNotExist): raise Http404 if thread.locked or (request.user != post.created_by and not request.user.is_superuser): return HttpResponseForbidden() if request.method == 'POST': postForm = PostForm(request.POST, instance=post, prefix='post') threadForm = ThreadForm(request.POST, instance=thread, prefix='thread') if postForm.is_valid(): postForm.save() if threadForm.is_valid(): threadForm.save() return HttpResponseRedirect(thread.relativeUrl) else: postForm = PostForm(instance=post, prefix='post') if request.user.is_superuser and thread.op == post: threadForm = ThreadForm(instance=thread, prefix='thread') else: threadForm = None postForm.fields['content'].label = '' context = dict(postForm=postForm, threadForm=threadForm, post_uid=post.uid, thread=thread, post=post) return render(request, 'djeddit/edit_post.html', context)
def get_map(request): """ Used by Ajax to get the results. """ if not request.is_ajax(): return HttpResponseForbidden("This URL if for Ajax only.") html = render_to_string("search/map.part.html") return HttpResponse(json.dumps({ "html_map": html, }), content_type="application/json" ) # Higher ratelimit, because users of light version may have # network troubles (like load interruptions).
def _check_access(request, func, *args, **kwargs): """ Checks user's authentication and access to repository. """ if request.META.get('HTTP_AUTHORIZATION'): user = base_auth(request.META['HTTP_AUTHORIZATION']) if user: repo = Repository.objects.get(owner=user, name=kwargs['repository']) access = RepositoryAccess.objects.get(user=user, repository=repo) if access: return func(request, *args, **kwargs) else: # User has no access to repository. return HttpResponseForbidden('Access forbidden.') else: # User is not registered on Djacket. return HttpResponseForbidden('Access forbidden.') res = HttpResponse() res.status_code = 401 # Basic authentication is needed. res['WWW-Authenticate'] = 'Basic' return res
def wfmodule_input(request, pk, format=None): if request.method == 'GET': try: wf_module = WfModule.objects.get(pk=pk) except WfModule.DoesNotExist: return HttpResponseNotFound() if not wf_module.user_authorized_read(request.user): return HttpResponseForbidden() # return empty table if this is the first module in the stack prev_modules = WfModule.objects.filter(workflow=wf_module.workflow, order__lt=wf_module.order) if not prev_modules: return HttpResponse(make_render_json(pd.DataFrame()), content_type="application/json") else: return table_result(request, prev_modules.last()) # Public access to wfmodule output. Basically just /render with different auth and output format # NOTE: does not support startrow/endrow at the moment
def wfmodule_dataversion(request, pk, format=None): try: wf_module = WfModule.objects.get(pk=pk) except WfModule.DoesNotExist: return HttpResponseNotFound() if request.method == 'GET': if not wf_module.user_authorized_read(request.user): return HttpResponseNotFound() versions = wf_module.list_fetched_data_versions() current_version = wf_module.get_fetched_data_version() response = {'versions': versions, 'selected': current_version} return Response(response) elif request.method == 'PATCH': if not wf_module.user_authorized_write(request.user): return HttpResponseForbidden() ChangeDataVersionCommand.create(wf_module, datetime.datetime.strptime(request.data['selected'], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.UTC)) return Response(status=status.HTTP_204_NO_CONTENT)
def workflow_duplicate(request, pk): try: workflow = Workflow.objects.get(pk=pk) except Workflow.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not workflow.user_authorized_read(request.user): return HttpResponseForbidden() workflow2 = workflow.duplicate(request.user) serializer = WorkflowSerializerLite(workflow2) return Response(serializer.data, status.HTTP_201_CREATED) # Undo or redo
def parameterval_detail(request, pk, format=None): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return HttpResponseNotFound() if request.method == 'GET': if not param.user_authorized_read(request.user): return HttpResponseNotFound() serializer = ParameterValSerializer(param) return Response(serializer.data) elif request.method == 'PATCH': if not param.user_authorized_write(request.user): return HttpResponseForbidden ChangeParameterCommand.create(param, request.data['value']) return Response(status=status.HTTP_204_NO_CONTENT) # Handle a parameter event (like someone clicking the fetch button) # Get or set parameter value
def parameterval_event(request, pk, format=None): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not param.user_authorized_write(request.user): return HttpResponseForbidden() # change parameter value data = request.data dispatch_response = module_dispatch_event(param.wf_module, parameter=param, event=data, request=request) if dispatch_response: return dispatch_response return Response(status=status.HTTP_204_NO_CONTENT) # Return a parameter val that is actually an image
def parameterval_png(request, pk): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return HttpResponseNotFound() if not param.wf_module.public_authorized(): return HttpResponseForbidden() # is this actually in image? totes hardcoded for now if param.parameter_spec.id_name != 'chart': return HttpResponseBadRequest() # decode the base64 payload of the data URI into a png image_data = param.value.partition('base64,')[2] binary = base64.b64decode(image_data) return HttpResponse(binary, content_type='image/png')
def signup(request, email_to_file=None): """Adds a new -inactive- user to the db. Send an email to an admin to validate the account. Not @protected because the user is unidentified at this point. """ logger.info("Signing up") username = request.POST['username'] password = request.POST['password'] firstname = request.POST['firstname'] lastname = request.POST['lastname'] email = request.POST['email'] phone = request.POST['phone'] if '_functest_' in username: email_to_file = open(os.devnull, 'w') user,msg = auth.create_user(username, password, firstname, lastname, email, phone, email_to_file) if user is None: return HttpResponseForbidden(msg) return JWT_user(user, TOKEN_DURATION)
def reset_password_request(request, email_to_file=None): """Does not actually change the password, but sends the user an email with a link to the change_password view to generate a new random one. Not @protected because the user is unidentified at this point. """ logger.info("Reset password request") username = request.POST['username'] email = request.POST['email'] host = request.POST['host'] if username == 'test': email_to_file = open(os.devnull, 'w') user,msg = auth.reset_password_request(username, email, host, email_to_file) if user is None: return HttpResponseForbidden(msg) user_info = {'username':username, 'email':email} return JsonResponse(user_info, safe=False)
def change_password(request, new_password=None, email_to_file=None): """Change a user's password and sends him an email with the new login. Also to validate password reset, in which case it replaces the user's password by a random one (if *password* is not set). Not @protected because the user is unidentified at this point, but the activation code is the protection. """ logger.info("Reset password validation") username = request.POST['username'] email = request.POST['email'] activation_code = request.POST['activation_code'] if new_password is None: new_password = utils.random_string(10) user,msg = auth.change_password(username, email, activation_code, new_password, email_to_file) if user is None: return HttpResponseForbidden(msg) return JWT_user(user, TOKEN_DURATION)
def change_attribute(request, user=None, **kwargs): """Change a user attribute such as email, role, etc.""" username = request.POST['username'] code = request.POST['code'] attribute = request.POST['attribute'] new_value = request.POST['new_value'] logger.info("Change attribute '{}'".format(attribute)) mod_user,msg = auth.change_attribute(username, code, attribute, new_value) # If the user changes himself, need to query again with possible changes if user.username == username and user.code == code: if attribute == 'username': user = auth.find_user(new_value, code) elif attribute == 'code': user = auth.find_user(username, new_value) else: user = auth.find_user(username, code) # If the user changes another user, check that he has the right to do it elif user.role.rank > 2: return HttpResponseForbidden("Insufficent credentials") return JWT_user(user, TOKEN_DURATION)
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_403_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
def glossurl(request, glossurl): if request.method == 'POST': glossurl = get_object_or_404(GlossURL, id=glossurl) if 'view_dataset' not in get_perms(request.user, glossurl.gloss.dataset): # If user has no permissions to dataset, raise PermissionDenied to show 403 template. msg = _("You do not have permissions to add tags to glosses of this lexicon.") messages.error(request, msg) raise PermissionDenied(msg) glossurl_id = glossurl.id try: glossurl.delete() except PermissionDenied: return HttpResponseForbidden('Permission Denied: Unable to delete GlossURL(id): ' + str(glossurl.id), content_type='text/plain') return HttpResponse('Deleted GlossURL(id): ' + str(glossurl_id), content_type='text/plain') else: return HttpResponseNotAllowed(permitted_methods=['POST'])
def edit_comment(request, id): """View to bind comment data to form and update comment.""" comment = get_object_or_404(Comment, id=id) # Make sure that only the commenter can edit the comment. if not request.user == comment.user: return HttpResponseForbidden(_("You are not allowed to edit this comment, " "because you are not the author of the comment.")) if request.method == 'POST': form = EditCommentForm(request.POST) if form.is_valid(): comment.comment = form.cleaned_data["comment"] comment.save() if form.cleaned_data["tag"]: tag = form.cleaned_data["tag"] Tag.objects.add_tag(comment, tag) if 'HTTP_REFERER' in request.META: return redirect(request.META['HTTP_REFERER']) else: return redirect(request.path) else: return bind_comment(request, comment)
def remove_tag(request): if request.method == 'POST': form = CommentRemoveTagForm(request.POST) if form.is_valid(): # Make sure that only the commenter can delete a tag. comment = get_object_or_404(Comment, id=form.cleaned_data["comment_id"]) if not request.user == comment.user or not request.user.is_staff: return HttpResponseForbidden(_("You are not allowed to edit tags of this comment, " "because you are not the author of the comment.")) if form.cleaned_data["remove_tag_id"]: tagged = get_object_or_404(TaggedItem, tag__id=form.cleaned_data["remove_tag_id"], object_id=comment.id) tagged.delete() if 'HTTP_REFERER' in request.META: return redirect(request.META['HTTP_REFERER']) else: return redirect(request.path)
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME): """ Permission denied (403) handler. :template: :file:`403.html` If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_403_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
def holds_lock_on_object(model, get_object_id_fn): def decorator(view): def wrapped(request, *args, **kwargs): object_id = get_object_id_fn(request, *args, **kwargs) obj = model.objects.get(id=object_id) try: lock_for_session(obj, request.session) except AlreadyLockedError: return HttpResponseForbidden("The object you are trying to access is " "locked.") lock_holder = LockHolder(obj) lock_holder.start() try: response = view(request, *args, **kwargs) finally: lock_holder.stop() unlock_for_session(obj, request.session) return response return wrapped return decorator
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """Replacement for django.contrib.auth.decorators.user_passes_test that returns 403 Forbidden if the user is already logged in. """ if not login_url: from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) elif request.user.is_authenticated(): return HttpResponseForbidden('<h1>Permission denied</h1>') else: path = '%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())) return HttpResponseRedirect(path) return wrapper return decorator
def revision_view(self, request, object_id, version_id, extra_context=None): if not is_installed('reversion'): return HttpResponseBadRequest('django reversion not installed') if not self.has_change_permission(request, Page.objects.get(pk=object_id)): raise PermissionDenied page = get_object_or_404(self.model, pk=object_id) if not page.publisher_is_draft: page = page.publisher_draft if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change this page"))) try: version = Version.objects.get(pk=version_id) clean = page._apply_revision(version.revision, set_dirty=True) if not clean: messages.error(request, _("Page reverted but slug stays the same because of url collisions.")) with create_revision(): adapter = self.revision_manager.get_adapter(page.__class__) self.revision_context_manager.add_to_context(self.revision_manager, page, adapter.get_version_data(page)) self.revision_context_manager.set_comment(_("Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)}) except IndexError as e: return HttpResponseBadRequest(e.message) return HttpResponseRedirect(admin_reverse('cms_page_change', args=(quote(object_id),)))
def undo(self, request, object_id): if not is_installed('reversion'): return HttpResponseBadRequest('django reversion not installed') page = get_object_or_404(self.model, pk=object_id) if not page.publisher_is_draft: page = page.publisher_draft if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change this page"))) try: reverted, clean = page.undo() if not clean: messages.error(request, _("Page reverted but slug stays the same because of url collisions.")) except IndexError as e: return HttpResponseBadRequest(e.message) return HttpResponse("ok")
def redo(self, request, object_id): if not is_installed('reversion'): return HttpResponseBadRequest('django reversion not installed') page = get_object_or_404(self.model, pk=object_id) if not page.publisher_is_draft: page = page.publisher_draft if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change this page"))) try: reverted, clean = page.redo() if not clean: messages.error(request, _("Page reverted but slug stays the same because of url collisions.")) except IndexError as e: return HttpResponseBadRequest(e.message) return HttpResponse("ok")
def change_template(self, request, object_id): page = get_object_or_404(self.model, pk=object_id) if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change the template"))) to_template = request.POST.get("template", None) if to_template not in dict(get_cms_setting('TEMPLATES')): return HttpResponseBadRequest(force_text(_("Template not valid"))) page.template = to_template page.save() if is_installed('reversion'): message = _("Template changed to %s") % dict(get_cms_setting('TEMPLATES'))[to_template] self.cleanup_history(page) helpers.make_revision_with_plugins(page, request.user, message) return HttpResponse(force_text(_("The template was successfully changed")))
def revert_page(self, request, page_id, language): page = get_object_or_404(self.model, id=page_id) # ensure user has permissions to publish this page if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change this page"))) page.revert(language) messages.info(request, _('The page "%s" was successfully reverted.') % page) if 'node' in request.GET or 'node' in request.POST: # if request comes from tree.. return HttpResponse(admin_utils.render_admin_menu_item(request, page)) # TODO: This should never fail, but it may be a POF path = page.get_absolute_url(language=language) path = '%s?%s' % (path, get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')) return HttpResponseRedirect(path)