Python django.http.HttpResponseForbidden() Examples
The following are 30
code examples of django.http.HttpResponseForbidden().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.http
, or try the search function
.
Example #1
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def remove_message(request, course_slug, topic_slug, message_slug): """ POST to remove a topic message """ course, view = _get_course_and_view(request, course_slug) if view is None: # course is an HttpResponse in this case return course if request.method != 'POST': raise Http404 topic = get_object_or_404(DiscussionTopic, slug=topic_slug, offering=course) message = get_object_or_404(DiscussionMessage, slug=message_slug, topic=topic) if view == 'staff' or message.author.person.userid == request.user.username: message.status = 'HID' message.save() messages.add_message(request, messages.SUCCESS, 'Reply successfully removed.') return HttpResponseRedirect(reverse('offering:discussion:view_topic', kwargs={'course_slug': course_slug, 'topic_slug': topic_slug})) else: return HttpResponseForbidden()
Example #2
Source File: views.py From anytask with MIT License | 6 votes |
def ajax_change_status(request): if not request.is_ajax(): return HttpResponseForbidden() post_dict = dict(request.POST) if 'statuses_id[]' in post_dict and 'profile_ids[]' in post_dict: statuses = UserStatus.objects.filter(id__in=post_dict['statuses_id[]']) for profile in UserProfile.objects.filter(id__in=post_dict['profile_ids[]']): for status in statuses: profile.set_status(status) post_save.send(UserProfile, instance=profile, created=False) reversion.set_user(request.user) reversion.set_comment("Change from user status bulk change") return HttpResponse("OK")
Example #3
Source File: views.py From anytask with MIT License | 6 votes |
def add_user_to_group(request): user = request.user if not request.method == 'POST': return HttpResponseForbidden() if 'group_id' not in request.POST: return HttpResponseForbidden() try: group_id = int(request.POST['group_id']) except ValueError: return HttpResponseForbidden() group = get_object_or_404(Group, id=group_id) group.students.add(user) group.save() return HttpResponse("OK")
Example #4
Source File: views.py From monasca-ui with Apache License 2.0 | 6 votes |
def dispatch(self, request, url): if not url: url = '/' if request.method not in self.http_method_names: return http.HttpResponseNotAllowed(request.method) if not self._can_access_kibana(): error_msg = (_('User %s does not have sufficient ' 'privileges to access Kibana') % auth_utils.get_user(request)) LOG.error(error_msg) return http.HttpResponseForbidden(content=error_msg) # passing kbn version explicitly for kibana >= 4.3.x headers = { "X-Auth-Token": request.user.token.id, "kbn-version": request.META.get("HTTP_KBN_VERSION", ""), "Cookie": request.META.get("HTTP_COOKIE", ""), "Content-Type": "application/json", } return self.read(request.method, url, request.body, headers)
Example #5
Source File: views.py From Pytition with BSD 3-Clause "New" or "Revised" License | 6 votes |
def image_upload(request): pytitionuser = get_session_user(request) if request.method != "POST": return HttpResponseForbidden() file = request.FILES.get('file', '') if file == '': return HttpResponseForbidden() storage = FileSystemStorage() path = os.path.join(storage.location, pytitionuser.username, file.name) name = storage._save(path, file) newrelpath = os.path.relpath(name, storage.location) return JsonResponse({'location': storage.base_url + newrelpath}) # /transfer_petition/<int:petition_id> # Transfer a petition to another org or user
Example #6
Source File: views.py From anytask with MIT License | 6 votes |
def get_issues(request, course_id): course = get_object_or_404(Course, id=course_id) user = request.user if not course.user_is_teacher(user): return HttpResponseForbidden() add_events = bool(request.GET.get("add_events", False)) filter_args = get_issue_filter(request.GET) ret = [] issues = Issue.objects \ .filter(task__course=course, **filter_args) \ .select_related("task") \ .prefetch_related("followers") lang = request.GET.get('lang', settings.API_LANGUAGE_CODE) for issue in issues: ret.append(unpack_issue(issue, add_events=add_events, request=request, lang=lang)) return HttpResponse(json.dumps(ret), content_type="application/json")
Example #7
Source File: Proxy.py From AnsibleUI with GNU General Public License v3.0 | 6 votes |
def ProxyAuth(func): @wraps(func) def wrapped_func(request, *args, **kw): # if not request.META.get("HTTP_WEICHAT_USER"): # return HttpResponseForbidden() # # return HttpResponse(status=403) # # return HttpResponseNotFound('<h1>Page not found</h1>') # pass # print("\33[36mURI %s\33[0m"%request.build_absolute_uri()) # print(dict((regex.sub('', header), value) for (header, value) # in request.META.items() if header.startswith('HTTP_'))) # print("\33[34mProxy: is_ajax:%s,WeiChat:[%s],AddR:[%s], Custome:[%s], X_F_F:%s, UA:%.10s\33[0m" % ( # request.is_ajax(), # request.META.get("HTTP_WEICHAT_USER", "None"), # request.META.get("REMOTE_ADDR", "None"), # request.META.get("HTTP_CUSTOMPROXY", "None"), # request.META.get("HTTP_X_FORWARDED_FOR", "None"), # request.META.get("HTTP_USER_AGENT", "None"), # )) print('is_ajax: %s' % request.is_ajax()) return func(request, *args, **kw) return wrapped_func
Example #8
Source File: decorators.py From browserscope with Apache License 2.0 | 6 votes |
def check_csrf(func): """Checks/removes a csrf_token from request.session's list of valid tokens.""" def _wrapper(request, *args, **kw): valid_csrf_tokens = request.session.get('csrf_tokens') request_csrf_token = request.REQUEST.get('csrf_token') # Special easter-egg to get around the csrf token. # Because most malintents don't really read code. if request.GET.get('csrf_override') == 'elsigh': return func(request, *args, **kw) if request_csrf_token is None: return HttpResponseForbidden('CSRF Error - Need csrf_token in request.') if request_csrf_token not in valid_csrf_tokens: return HttpResponseForbidden('CSRF Error - Invalid csrf_token.') request.session['csrf_token'] = None request.session['csrf_tokens'].remove(request_csrf_token) return func(request, *args, **kw) return _wrapper
Example #9
Source File: views.py From anytask with MIT License | 6 votes |
def contest_import_page(request, course_id): course = get_object_or_404(Course, id=course_id) if not course.user_is_teacher(request.user): return HttpResponseForbidden() schools = course.school_set.all() seminar_tasks = Task.objects.filter(type=Task().TYPE_SEMINAR).filter(course=course) context = { 'is_create': True, 'course': course, 'rb_integrated': course.rb_integrated, 'seminar_tasks': seminar_tasks, 'school': schools[0] if schools else '', 'contest_import': True, 'user_location': request.user.profile.location, 'geo_suggest_url': settings.GEO_SUGGEST_URL } return render(request, 'contest_import.html', context)
Example #10
Source File: views.py From anytask with MIT License | 6 votes |
def task_import_page(request, course_id): course = get_object_or_404(Course, id=course_id) if not course.user_is_teacher(request.user): return HttpResponseForbidden() schools = course.school_set.all() seminar_tasks = Task.objects.filter(type=Task().TYPE_SEMINAR).filter(course=course) context = { 'is_create': True, 'course': course, 'rb_integrated': course.rb_integrated, 'school': schools[0] if schools else '', 'seminar_tasks': seminar_tasks, 'user_location': request.user.profile.location, 'geo_suggest_url': settings.GEO_SUGGEST_URL } return render(request, 'task_import.html', context)
Example #11
Source File: views.py From anytask with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): if 'HTTP_AUTHORIZATION' in request.META: auth_str = request.META['HTTP_AUTHORIZATION'] auth_str_parts = auth_str.split() if auth_str_parts[0] != "Basic": return HttpResponseForbidden() username, password = base64.b64decode(auth_str_parts[1]).split(":", 1) svn_url = request.META.get('HTTP_REFERER', '') if not svn_url.startswith(settings.ANYSVN_SVN_URL_PREFIX): return HttpResponse() return HttpResponseUnauthorized() svn_path = svn_url[len(settings.ANYSVN_SVN_URL_PREFIX):] if svn_path and "/" in svn_path: svn_path = svn_path.split("/")[0] if self.check_svn_access_and_ensure_exists(svn_path, username, password): return HttpResponse() return HttpResponseUnauthorized()
Example #12
Source File: views.py From anytask with MIT License | 6 votes |
def schedule_edit_page(request, lesson_id): lssn = get_object_or_404(Lesson, id=lesson_id) if not lssn.course.user_is_teacher(request.user): return HttpResponseForbidden() if request.method == 'POST': return lesson_edit(request, lssn.course, lesson_id) schools = lssn.course.school_set.all() context = { 'is_create': False, 'course': lssn.course, 'lesson': lssn, 'period_types': lssn.PERIOD_CHOICES, 'school': schools[0] if schools else '', 'user_location': request.user.profile.location, 'geo_suggest_url': settings.GEO_SUGGEST_URL } return render(request, 'lesson_edit.html', context)
Example #13
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def edit_message(request, course_slug, topic_slug, message_slug): """ Form to edit a recently posted reply (5 min window) """ course, view = _get_course_and_view(request, course_slug) if view is None: # course is an HttpResponse in this case return course topic = get_object_or_404(DiscussionTopic, slug=topic_slug, offering=course) message = get_object_or_404(DiscussionMessage, slug=message_slug, topic=topic) if not message.author.person.userid == request.user.username: return HttpResponseForbidden if (datetime.datetime.now() - message.created_at) > datetime.timedelta(minutes = 5): raise Http404 if request.method == 'POST': form = DiscussionMessageForm(data=request.POST, instance=message) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Reply successfully edited.') return HttpResponseRedirect(reverse('offering:discussion:view_topic', kwargs={'course_slug': course_slug, 'topic_slug': topic.slug})) else: form = DiscussionMessageForm(instance=message) return render(request, 'discuss/edit_reply.html', {'course':course, 'topic': topic, 'message': message, 'form': form})
Example #14
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def change_topic_status(request, course_slug, topic_slug): """ Form to change the status of a topic """ course, view = _get_course_and_view(request, course_slug) if view is None: # course is an HttpResponse in this case return course topic = get_object_or_404(DiscussionTopic, slug=topic_slug, offering=course) if view is not 'staff': return HttpResponseForbidden() if request.method == 'POST': form = DiscussionTopicStatusForm(request.POST, instance=topic) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Discussion topic has been successfully changed.') return HttpResponseRedirect(reverse('offering:discussion:view_topic', kwargs={'course_slug': course_slug, 'topic_slug': topic.slug})) else: form = DiscussionTopicStatusForm(instance=topic) return render(request, 'discuss/change_topic.html', {'course': course, 'topic': topic, 'form': form})
Example #15
Source File: views.py From anytask with MIT License | 6 votes |
def schedule_create_page(request, course_id): course = get_object_or_404(Course, id=course_id) if not course.user_is_teacher(request.user): return HttpResponseForbidden() if request.method == 'POST': return lesson_create(request, course) schools = course.school_set.all() context = { 'is_create': True, 'course': course, 'period_types': Lesson().PERIOD_CHOICES, 'school': schools[0] if schools else '', 'user_location': request.user.profile.location, 'geo_suggest_url': settings.GEO_SUGGEST_URL } return render(request, 'lesson_create.html', context)
Example #16
Source File: views.py From peering-manager with Apache License 2.0 | 6 votes |
def configure(self, request, pk=None): router = self.get_object() # Check if the router runs on a supported platform if not router.platform: raise ServiceUnavailable("Unsupported router platform.") # Check user permission first if not request.user.has_perm("peering.deploy_configuration_router"): return HttpResponseForbidden() # Commit changes only if not using a GET request error, changes = router.set_napalm_configuration( router.generate_configuration(), commit=(request.method not in SAFE_METHODS) ) return Response({"changed": not error, "changes": changes, "error": error})
Example #17
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def reject(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) person = get_object_or_404(Person, userid = request.user.username) member = get_object_or_404(Member, person = person, offering=course) if request.method != "POST": return HttpResponseForbidden() # delete membership on reject GroupMember.objects.filter(group = group, student = member).delete() #LOG EVENT# l = LogEntry(userid=request.user.username, description="rejected membership in group %s." % (group.name,), related_object=group ) l.save() messages.add_message(request, messages.SUCCESS, 'You have left the group "%s".' % (group.name)) return HttpResponseRedirect(reverse('offering:groups:groupmanage', kwargs={'course_slug': course_slug}))
Example #18
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def join(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) person = get_object_or_404(Person, userid = request.user.username) member = get_object_or_404(Member, person = person, offering=course) if request.method != "POST": return HttpResponseForbidden() for groupMember in GroupMember.objects.filter(group = group, student = member): groupMember.confirmed = True groupMember.save() #LOG EVENT# l = LogEntry(userid=request.user.username, description="joined group %s." % (group.name,), related_object=group ) l.save() messages.add_message(request, messages.SUCCESS, 'You have joined the group "%s".' % (group.name)) return HttpResponseRedirect(reverse('offering:groups:groupmanage', kwargs={'course_slug': course_slug}))
Example #19
Source File: controller.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
def disabled_when_voting(func: Callable) -> Callable: """A decorator for controls that are disabled during voting. Only users with appropriate privileges are still able to perform this action.""" def _decorator( self: "Controller", request: WSGIRequest, *args, **kwargs ) -> HttpResponse: if ( self.musiq.base.settings.basic.voting_system and not self.musiq.base.user_manager.has_controls(request.user) ): return HttpResponseForbidden() func(self, request, *args, **kwargs) self.musiq.update_state() return HttpResponse() return wraps(func)(_decorator)
Example #20
Source File: views.py From telemetry-analysis-service with Mozilla Public License 2.0 | 6 votes |
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)}) )
Example #21
Source File: settings.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
def option( func: Callable[[T, WSGIRequest], Optional[HttpResponse]] ) -> Callable[[T, WSGIRequest], HttpResponse]: """A decorator that makes sure that only the admin changes a setting.""" def _decorator(self: T, request: WSGIRequest) -> HttpResponse: # don't allow option changes during alarm if request.user.username != "admin": return HttpResponseForbidden() response = func(self, request) self.base.settings.update_state() if response is not None: return response return HttpResponse() return wraps(func)(_decorator)
Example #22
Source File: views.py From anytask with MIT License | 6 votes |
def ajax_edit_user_info(request): if not request.method == 'POST' and not request.is_ajax(): return HttpResponseForbidden() user = request.user user_profile = user.profile user_info = '' if 'user-info' in request.POST: user_info = request.POST['user-info'].strip() if user_info and not user_info.startswith(u'<div class="not-sanitize">'): user_info = u'<div class="not-sanitize">' + user_info + u'</div>' user_profile.info = user_info user_profile.save() return HttpResponse(json.dumps({'info': user_info}), content_type="application/json")
Example #23
Source File: views.py From anytask with MIT License | 5 votes |
def ajax_search_courses(request): if 'q' not in request.GET: return HttpResponseForbidden() if 'max' in request.GET: max_result = int(request.GET["max"]) else: max_result = 3 result, _ = search_courses(request.GET.get('q', ''), request.user, max_result + 1) return HttpResponse(json.dumps({'result': result[:max_result], 'is_limited': True if len(result) > max_result else False}), content_type='application/json')
Example #24
Source File: views.py From anytask with MIT License | 5 votes |
def get_issue_statuses(request, course_id): user = request.user course = get_object_or_404(Course, id=course_id) if not course.user_is_teacher(user): return HttpResponseForbidden() ret = unpack_statuses(course) return HttpResponse(json.dumps(ret), content_type="application/json")
Example #25
Source File: views.py From tom_base with GNU General Public License v3.0 | 5 votes |
def delete(self, request, *args, **kwargs): """ Method that handles the DELETE request for a ``Comment``. Validates that the user either authored the comment or is a superuser, then deletes the ``Comment``. """ if request.user == self.get_object().user or request.user.is_superuser: self.success_url = self.get_object().get_absolute_url() return super().delete(request, *args, **kwargs) else: return HttpResponseForbidden('Not authorized')
Example #26
Source File: middleware.py From KortURL with MIT License | 5 votes |
def __call__(self, request): ip = self.get_ip_address(request) rate = config.rate if self.can_access(ip, rate): response = self.get_response(request) else: response = HttpResponseForbidden("亲,访问频率太快了,休息一下吧") return response
Example #27
Source File: views.py From anytask with MIT License | 5 votes |
def add_comment(request, issue_id): comment = request.POST.get('comment') if not comment: return HttpResponseBadRequest() user = request.user issue = get_object_or_404(Issue, id=issue_id) if not has_access(user, issue): return HttpResponseForbidden() issue.add_comment(comment, author=user) return HttpResponse(status=201)
Example #28
Source File: views.py From anytask with MIT License | 5 votes |
def get_or_post_issue(request, issue_id): issue = get_object_or_404(Issue, id=issue_id) if not has_access(request.user, issue): return HttpResponseForbidden() if request.method == 'POST': return post_issue(request, issue) return get_issue(request, issue)
Example #29
Source File: views.py From anytask with MIT License | 5 votes |
def task_create_page(request, course_id): course = get_object_or_404(Course, id=course_id) if not course.user_is_teacher(request.user): return HttpResponseForbidden() if request.method == 'POST': return task_create_or_edit(request, course) schools = course.school_set.all() seminar_tasks = Task.objects.filter(type=Task().TYPE_SEMINAR).filter(course=course) not_seminar_tasks = Task.objects.filter(~Q(type=Task().TYPE_SEMINAR)).filter(course=course) has_seminar = course.issue_status_system.statuses.filter(tag=IssueStatus.STATUS_SEMINAR).count() task_types = Task.TASK_TYPE_CHOICES if not has_seminar: task_types = filter(lambda x: not x[0] == Task.TYPE_SEMINAR, task_types) context = { 'is_create': True, 'course': course, 'task_types': task_types, 'seminar_tasks': seminar_tasks, 'not_seminar_tasks': not_seminar_tasks, 'contest_integrated': course.contest_integrated, 'rb_integrated': course.rb_integrated, 'hide_contest_settings': True if not course.contest_integrated else False, 'school': schools[0] if schools else '', 'user_location': request.user.profile.location, 'geo_suggest_url': settings.GEO_SUGGEST_URL } return render(request, 'task_create.html', context)
Example #30
Source File: middleware.py From django-user-activity-log with MIT License | 5 votes |
def process_response(self, request, response): try: self._write_log(request, response, getattr(request, 'saved_body', '')) except DisallowedHost: return HttpResponseForbidden() return response