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})
python类HttpResponseForbidden()的实例源码
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 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 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)