Python django.http.HttpResponseForbidden() Examples

The following are 30 code examples for showing how to use django.http.HttpResponseForbidden(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: peering-manager   Author: respawner   File: views.py    License: Apache License 2.0 7 votes vote down vote up
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 2
Project: raveberry   Author: raveberry   File: controller.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 3
Project: raveberry   Author: raveberry   File: settings.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 4
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 8
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 9
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 6 votes vote down vote up
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 10
Project: AnsibleUI   Author: lotus-dgas   File: Proxy.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 11
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 12
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 13
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 14
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 15
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 16
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 17
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 18
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 19
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 20
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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 21
Project: monasca-ui   Author: openstack   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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 22
Project: Pytition   Author: pytition   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 23
Project: raveberry   Author: raveberry   File: controller.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def remove_all(self, request: WSGIRequest) -> HttpResponse:
        """Empties the queue. Only admin is permitted to do this."""
        if not self.musiq.base.user_manager.is_admin(request.user):
            return HttpResponseForbidden()
        with self.playback.mopidy_command() as allowed:
            if allowed:
                with transaction.atomic():
                    count = self.playback.queue.count()
                    self.playback.queue.all().delete()
                for _ in range(count):
                    self.playback.queue_semaphore.acquire(blocking=False)
        return HttpResponse() 
Example 24
Project: raveberry   Author: raveberry   File: lights.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def option(
    func: Callable[["Lights", WSGIRequest], Optional[HttpResponse]]
) -> Callable[["Lights", WSGIRequest], HttpResponse]:
    """A decorator that makes sure that all changes to the lights are synchronized."""

    def _decorator(self: "Lights", request: WSGIRequest) -> HttpResponse:
        # only privileged users can change options during voting system
        if (
            self.base.settings.basic.voting_system
            and not self.base.user_manager.has_controls(request.user)
        ):
            return HttpResponseForbidden()
        # don't allow option changes during alarm
        if self.base.musiq.playback.alarm_playing.is_set():
            return HttpResponseForbidden()
        with self.option_lock:
            try:
                response = func(self, request)
                if response is not None:
                    return response
            except (ValueError, IndexError) as e:
                logging.exception("exception during lights option: %s", e)
                return HttpResponseBadRequest()
            self.update_state()
        return HttpResponse()

    return wraps(func)(_decorator) 
Example 25
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create(request, course_slug):
    person = get_object_or_404(Person, userid=request.user.username)
    course = get_object_or_404(CourseOffering, slug=course_slug)
    span = course.group_span_activities()

    # allow 'activity=foo' in query string to suggest default selected for the form
    if 'activity' in request.GET:
        selected_activity = get_object_or_404(Activity, offering=course, slug=request.GET['activity'], status__in=['RLS','URLS'])
    else:
        selected_activity = None

    group_manager = Member.objects.exclude(role="DROP").get(person = person, offering = course)
    groupForSemesterForm = GroupForSemesterForm()
    activities = Activity.objects.exclude(status='INVI').filter(offering=course, group=True, deleted=False)
    activityList = []
    for activity in activities:
        default = (span and not selected_activity) or (selected_activity and activity == selected_activity)
        activityForm = ActivityForm(prefix=activity.slug, initial={'selected': default})
        activityList.append({'activityForm': activityForm, 'name': activity.name,
                             'percent': activity.percent, 'due_date': activity.due_date})

    if is_course_student_by_slug(request, course_slug):
        return render(request, 'groups/create_student.html',
                                  {'manager':group_manager, 'course':course, 'groupForSemester':groupForSemesterForm, 'activityList':activityList})

    elif is_course_staff_by_slug(request, course_slug):
        #For instructor page, there is a student table for him/her to choose the students who belong to the new group
        students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
        studentList = []
        for student in students:
            studentForm = StudentForm(prefix = student.person.userid)
            studentList.append({'studentForm': studentForm, 'first_name' : student.person.first_name,\
                                 'last_name' : student.person.last_name, 'userid' : student.person.userid,\
                                 'emplid' : student.person.emplid})

        return render(request, 'groups/create_instructor.html',
                          {'manager':group_manager, 'course':course,'groupForSemester':groupForSemesterForm, 'activityList':activityList, \
                           'studentList':studentList})
    else:
        return HttpResponseForbidden() 
Example 26
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_course_and_view(request, course_slug):
    """
    Validates the request and returns the course object and view perspective ('student', 'staff')
    """
    course = get_object_or_404(CourseOffering, slug=course_slug)
    if not course.discussion():
        raise Http404
    if is_course_student_by_slug(request, course_slug):
        return course, 'student'
    elif is_course_staff_by_slug(request, course_slug):
        return course, 'staff'
    else:
        return HttpResponseForbidden(), None 
Example 27
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request):
        # Override to catch exceptions caused by CAS server not responding, which happens and is beyond our control.
        try:
            return super().get(request)
        except IOError as e:
            # Ignore a minimal set of errors we have actually seen result from CAS outages
            if e.errno in [104, 110, 'socket error']:
                pass

            # HTTPError is a subclass of OSError, which IOError is an alias for.
            # Sometimes, the CAS server seems to just return a 500 internal server error.  Let's handle that the
            # same way as the above case.
            elif isinstance(e, HTTPError):
                if e.code == 500:
                    pass
                else:
                    # Any other HTTPError should bubble up and let us know something horrible has happened.
                    raise HTTPError("Got an HTTP Error when authenticating. The error is: {0!s}.".format(e))

            else:
                raise IOError("The errno is %r: %s." % (e.errno, str(e)))

        except ParseError:
            pass

        error = "<h1>Forbidden</h1><p>Login failed because of a CAS error.</p>"
        return HttpResponseForbidden(error) 
Example 28
Project: coursys   Author: sfu-fas   File: throttle.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        # ignore anything starting with an excluded path
        for prefix in EXCLUDE:
            if request.path.startswith(prefix):
                return

        key = self.request_key(request)
        if cache.get(key):
            return HttpResponseForbidden("Slow down.", content_type="text/plain")
        cache.set(key, True, THROTTLE_TIME) 
Example 29
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def manage_memo(request, userid, event_slug, memo_slug):
    person, member_units = _get_faculty_or_404(request.units, userid)
    instance = _get_event_or_404(units=request.units, slug=event_slug, person=person)
    memo = get_object_or_404(Memo, slug=memo_slug, career_event=instance)

    handler = instance.get_handler()
    if not handler.can_view(person):
        return HttpResponseForbidden(request, "Not allowed to view this memo")

    if request.method == 'POST':
        form = MemoForm(request.POST, instance=memo)
        if form.is_valid():
            with transaction.atomic():
                f = form.save(commit=False)
                f.career_event = instance
                f.config['pdf_generated'] = False
                uneditable_reason = memo.uneditable_reason()
                if uneditable_reason:
                    orig_pk = f.pk
                    f.pk = None
                    f.save()
                    Memo.objects.filter(pk=orig_pk).update(hidden=True)
                    messages.success(request, "Saved new version of memo.")
                else:
                    f.save()
                    messages.success(request, "Edited memo.")
            return HttpResponseRedirect(reverse('faculty:view_event', kwargs={'userid':userid, 'event_slug':event_slug}))
    else:
        form = MemoForm(instance=memo)

    context = {
               'form': form,
               'person': person,
               'event': instance,
               'memo': memo,
               }
    return render(request, 'faculty/manage_memo.html', context) 
Example 30
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def _check_csrf(func, request, *args, **kw):
  """Checks/removes a csrf_token from request.session's list of valid tokens."""
  valid_csrf_tokens = request.session.get('csrf_tokens')
  request_csrf_token = request.REQUEST.get('csrf_token')

  # Special exemption for Safari usertest results.
  # TODO(elsigh): Maybe there's a better way to handle the fact that
  # Safari won't accept third-party cookies?
  if valid_csrf_tokens is None and isSafariAndUserTest(request):
    logging.info('SAFARI USER-TEST EXCEPTION for check_csrf')
    return func(request, *args, **kw)

  if request_csrf_token is None:
    msg = 'CSRF Error - Need csrf_token in request.'
    logging.info(msg)
    return HttpResponseForbidden(msg)
  if valid_csrf_tokens is None or request_csrf_token not in valid_csrf_tokens:
    msg = 'CSRF Error - Invalid csrf_token.'
    request.session['csrf_tokens'] = None
    logging.info(msg)
    return HttpResponseForbidden(msg)

  request.session['csrf_token'] = None
  request.session['csrf_tokens'].remove(request_csrf_token)

  return func(request, *args, **kw)