django.http.HttpResponseForbidden

Here are the examples of the python api django.http.HttpResponseForbidden taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: hubplus
Source File: middleware.py
View license
  def process_response(self, request, response):
    # If the response object is a vanilla 403 constructed with
    # django.http.HttpResponseForbidden() then call our custom 403 view
    # function
    if isinstance(response, django.http.HttpResponseForbidden) and \
        set(dir(response)) == set(dir(django.http.HttpResponseForbidden())):
      import views
      try:
        return views.access_denied(request)
      except django.template.TemplateDoesNotExist, e:
        return views.fallback_403(request)

    return response

Example 2

Project: kobocat
Source File: views.py
View license
def readable_xform_required(func):
    def _wrapper(request, username, id_string):
        owner = get_object_or_404(User, username=username)
        xform = get_object_or_404(owner.xforms, id_string=id_string)
        if not has_permission(xform, owner, request):
            return HttpResponseForbidden(_(u'Not shared.'))
        return func(request, username, id_string)
    return _wrapper

Example 3

Project: django-nosqladmin
Source File: mixins.py
View license
    def render_to_response(self, context, **response_kwargs):
        if hasattr(self, 'permission') and self.permission not in context:
            return HttpResponseForbidden("You do not have permissions to access this content.")

        return self.response_class(
            request = self.request,
            template = self.get_template_names(),
            context = context,
            **response_kwargs
        )

Example 4

View license
def debug_required(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        if not getattr(settings, 'DEBUG_TOOLBAR_USER_DEBUG', settings.DEBUG):
            return HttpResponseForbidden()
        return fn(*args, **kwargs)
    return wrapper

Example 5

Project: betafarm
Source File: views.py
View license
    @method_decorator(login_required)
    def post(self, request, pk):
        link = get_object_or_404(Link, pk=pk)
        if not request.user.get_profile().owns_project(link.project):
            return HttpResponseForbidden()
        link.delete()
        if request.is_ajax():
            return HttpResponse(status=204)
        return redirect('projects_show', slug=link.project.slug)

Example 6

Project: wagtail
Source File: collections.py
View license
    def post(self, request, instance_id):
        self.instance = get_object_or_404(self.get_queryset(), id=instance_id)
        collection_contents = self.get_collection_contents()

        if collection_contents:
            # collection is non-empty; refuse to delete it
            return HttpResponseForbidden()

        self.instance.delete()
        messages.success(request, self.success_message.format(self.instance))
        return redirect(self.index_url_name)

Example 7

Project: otm-core
Source File: user.py
View license
def update_profile_photo(request, user_id):
    user = get_object_or_404(User, pk=user_id)

    if user.pk != request.user.pk:
        return HttpResponseForbidden()

    return upload_user_photo(request, user)

Example 8

Project: airmozilla
Source File: views.py
View license
def must_be_your_event(f):
    @wraps(f)
    def inner(request, id, **kwargs):
        assert request.user.is_authenticated()
        event = get_object_or_404(Event, pk=id)
        if event.creator != request.user:
            return http.HttpResponseForbidden(
                "Not your event to meddle with"
            )
        return f(request, event, **kwargs)

    return inner

Example 9

Project: django-urlcrypt
Source File: views.py
View license
def rate_limit(num=60):
    """
    Limits the number of requests made by a unique visitor to this view to num per minute.
    """
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            cache_key = 'rate_limit.%s' % request.session._session_key
            added = cache.add(cache_key, 1, timeout=60)
            if added:
                num_tries = 1
            else:
                num_tries = cache.incr(cache_key, delta=1)
            if num_tries > num:
                raise HttpResponseForbidden("Rate Limit Exceeded")
            return func(request, *args, **kwargs)
        return wrapper
    return decorator

Example 10

Project: djep
Source File: views.py
View license
    def get(self, request, pk):
        if not request.user.is_staff:
            return HttpResponseForbidden()
        ctype = get_object_or_404(ContentType.objects, pk=pk).model_class()
        if not issubclass(ctype, Ticket):
            raise Http404()
        result = [{'name': name, 'label': unicode(ctype._meta.get_field(name).verbose_name)} for name in ctype.get_fields()]
        return HttpResponse(json.dumps(result),
                content_type='text/json')

Example 11

Project: dissemin
Source File: views.py
View license
@user_passes_test(is_authenticated)
def refetchResearcher(request, pk):
    researcher = get_object_or_404(Researcher, pk=pk)
    if researcher.user != request.user and not request.user.is_staff:
        return HttpResponseForbidden("Not authorized to update papers for this researcher.")
    from backend.tasks import fetch_everything_for_researcher
    fetch_everything_for_researcher.delay(pk=pk)
    return redirect(request.META['HTTP_REFERER'])

Example 12

Project: tendenci
Source File: views.py
View license
    def dispatch(self, request, *args, **kwargs):
        try:
            return super(RedirectToLoginMixin, self).dispatch(request, *args, **kwargs)
        except PermissionDenied:
            if not request.user.is_authenticated():
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(self.get_login_redirect_url())
            else:
                return HttpResponseForbidden()

Example 13

Project: make.mozilla.org
Source File: views.py
View license
def verified_ownership(f):
    def wrapped(request, event_hash):
        event = get_object_or_404(models.Event, url_hash=event_hash)
        if not event.verify_ownership(request.user):
            return http.HttpResponseForbidden(u'sorry, you’re not allowed in')
        return f(request, event)
    return wrapped

Example 14

Project: davvy
Source File: base.py
View license
    def delete(self, request, user, resource_name):
        resource = self.get_resource(request, user, resource_name)

        # you can't delete protected resources
        if resource.protected:
            return HttpResponseForbidden()

        depth = request.META.get('HTTP_DEPTH', 'infinity')
        # return forbidden if there are still items in the collection and
        # Depth is not 'infinity'
        # this is not standard-compliant, but should increase security
        if resource.collection and depth != 'infinity':
            if resource.resource_set.count() > 0:
                return HttpResponseForbidden()
        resource.delete()
        return HttpResponse(status=204)

Example 15

Project: huxley
Source File: views.py
View license
def login_as_user(request, uid):
    '''Log in as a particular user (admin use only).'''
    try:
        if not request.user.is_superuser:
            return HttpResponseForbidden()

        username = User.objects.get(id=uid).username
        user = authenticate(username=username, password=settings.ADMIN_SECRET)
        login(request, user)

        return HttpResponseRedirect(reverse('www:index'))

    except User.DoesNotExist:
        return HttpResponseNotFound()

Example 16

Project: wolnelektury
Source File: utils.py
View license
def require_login(request):
    """Return 403 if request is AJAX. Redirect to login page if not."""
    if request.is_ajax():
        return HttpResponseForbidden('Not logged in')
    else:
        return HttpResponseRedirect('/uzytkownicy/zaloguj')  # next?=request.build_full_path())

Example 17

Project: frigg-hq
Source File: decorators.py
View license
def worker_token_required(view_func):
    @csrf_exempt
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        token = request.META.get('HTTP_FRIGG_WORKER_TOKEN')
        if token:
            if token in getattr(settings, 'FRIGG_WORKER_TOKENS', []):
                return view_func(request, *args, **kwargs)
        return HttpResponseForbidden()
    return _wrapped_view

Example 18

Project: evething
Source File: account.py
View license
def account_register(request):
    """Register Account"""
    if not settings.ALLOW_REGISTRATION:
        return HttpResponseForbidden()

    if request.user.is_authenticated():
        return redirect(reverse('home'))

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('home'))
    else:
        form = UserCreationForm()

    return render(request, "registration/register.html", {
        'form': form,
    })

Example 19

Project: django-fancy-autocomplete
Source File: views.py
View license
    def __call__(self, request):
        """
        Handle an autocomplete request.
        """
        self.request = request
        if request.method not in self.allowed_methods:
            return HttpResponseNotAllowed(self.allowed_methods)
        if not self.is_authorized():
            return HttpResponseForbidden()
        results = self.get_result_queryset()
        return self.get_response(results)

Example 20

View license
def file_view(request, fname):
    """A view that echoes back what it receives."""
    if not request.user.is_staff:
        return HttpResponseForbidden()

    if request.method != 'GET':
        return HttpResponseBadRequest()

    storage = DatabaseStorage()
    f = storage.open(fname, 'rb')
    if f is None:
        return HttpResponseNotFound()
    ftype, _ = mimetypes.guess_type(fname)
    response = HttpResponse(f.read(), content_type=ftype or 'application/octet-stream')
    response['Content-Disposition'] = 'inline; filename=%s' % fname
    response['Content-Length'] = '%d' % f.size
    return response

Example 21

View license
def product_list_view(request):
    if request.is_authenticated():
        ctx = {'products': Product.objects.all(),
               'categories_count': len(Category.objects.all())}
        return render(request, 'product_list.html', context=ctx)
    else:
        return HttpResponseForbidden()

Example 22

Project: onlineweb4
Source File: views.py
View license
@require_http_methods(["POST"])
@login_required
def vote(request):
    m = get_active_meeting()
    if m:
        a = anonymous_voter(request.COOKIES.get('anon_voter'), request.user.username)
        r = RegisteredVoter.objects.filter(user=request.user, meeting=m).first()

        # If user is logged in
        if a:
            return handle_user_vote(request, m, a, r)
    return HttpResponseForbidden()

Example 23

Project: pybbm
Source File: views.py
View license
    def dispatch(self, request, *args, **kwargs):
        try:
            return super(RedirectToLoginMixin, self).dispatch(request, *args, **kwargs)
        except PermissionDenied:
            if not request.user.is_authenticated():
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(self.get_login_redirect_url())
            else:
                return HttpResponseForbidden()

Example 24

Project: django-objectpermissions
Source File: views.py
View license
def permission_denied(request, template_name=None, extra_context={}):
    """
    Default 403 handler.

    Templates: `403.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    if template_name is None:
        template_name = ('403.html',)
    context = {
        'request_path': request.path,
    }
    context.update(extra_context)
    return HttpResponseForbidden(loader.render_to_string(template_name, context,
                                 context_instance=RequestContext(request)))

Example 25

Project: canvas
Source File: views.py
View license
@require_POST
@csrf_exempt
def deauthorize_facebook_user(request):
    signed_request = request.POST.get(u'signed_request', None)

    if not signed_request:
        return HttpResponseForbidden('403 Forbidden')

    data = parse_signed_request(request, signed_request)
    fb_uid = data['user_id']

    fb_user = FacebookUser.objects.get(fb_uid=int(fb_uid))
    fb_user.delete()

    Metrics.facebook_user_deauthorized.record(request)

    return HttpResponse('success')

Example 26

Project: forum
Source File: views.py
View license
def permission_denied(request, title='Permission denied',
    message='You do not have permission to perform the requested action.'):
    """
    Returns an HttpResponseForbidden with a permission denied error
    screen.
    """
    return HttpResponseForbidden(loader.render_to_string(
        'forum/permission_denied.html', {
            'title': title,
            'message': message,
        }))

Example 27

Project: web
Source File: views.py
View license
    def dispatch(self, request, *args, **kwargs):
        handler = super(DocumentEdit, self).dispatch(request, *args, **kwargs)
        # Only allow editing if current user is owner
        if self.object.uploader != request.user:
            return HttpResponseForbidden('Du darfst keine fremden Uploads editieren.')
        return handler

Example 28

Project: cgstudiomap
Source File: views.py
View license
def with_origin(func):
    @wraps(func)
    def wrapped(request, *args, **kwargs):
        origin = request.META.get('HTTP_ORIGIN')

        if not is_valid_origin(origin):
            return HttpResponseForbidden()

        response = func(request, *args, **kwargs)
        response['Access-Control-Allow-Origin'] = origin
        response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'

        return response
    return wrapped

Example 29

Project: idea-color-themes
Source File: themes.py
View license
@view(path=r'^themes/download-all-archive/?')
def download_all_archive(request):
    token_value = request.session.get('shopping_token', None)
    if allow_download_all(token_value):
        archive = get_all_themes_archive()
        resp = http.HttpResponse(archive, mimetype='application/x-zip-compressed')
        resp['Content-Disposition'] = 'attachment; filename=all-idea-color-themes.zip'
        return resp

    return HttpResponseForbidden()

Example 30

Project: oioioi
Source File: views.py
View license
def handler403(request):
    if request.is_ajax():
        return HttpResponse('403 Forbidden', status=403,
                content_type='text/plain')
    message = render_to_string('403.html',
            context_instance=RequestContext(request))
    return HttpResponseForbidden(message)

Example 31

Project: Django--an-app-at-a-time
Source File: common.py
View license
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.scheme,
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    pass
        return self.response_redirect_class(newurl)

Example 32

Project: hubplus
Source File: decorators.py
View license
def secure_resource(cls=None, with_interfaces=None, required_interfaces=None, obj_schema=None):
    def decorator(f):
        if cls:
            def g(request, resource_id, *args, **kwargs):
                try:
                    sec_resource =  secure(request, cls, resource_id, required_interfaces, with_interfaces)
                except PlusPermissionsNoAccessException:
                    return HttpResponseForbidden(
                        "User %s is not authorized to call %s with interface %s" % (request.user, get_resource(cls, resource_id), required_interfaces[0])
                    )
                return f(request, sec_resource, *args,**kwargs)
            return g
        elif obj_schema:

            def g(request, *args, **kwargs):

                if request.POST:
                    data = request.POST.copy() 
                elif request.GET:
                    data = request.GET.copy()
                data.update(kwargs) # added because we want to keep some params to view eg. class and id in the URL

                for obj_key, obj_types in obj_schema.iteritems():
                    if isinstance(obj_types, list) and len(obj_types) == 1:
                        cls = obj_types[0]
                    elif obj_types == 'any' or isinstance(obj_types, list):
                        classname = data.get(obj_key + '_class', None)
                        if classname:
                            cls = ContentType.objects.get(model=classname.lower()).model_class()
                            if isinstance(obj_types, list):
                                if cls not in obj_types:
                                    raise TypeError(cls.__name__ + " not in " + `list`)
                        else:
                            continue

                    id = data.get(obj_key, None) or data.get(obj_key +'_id', None)
                    required = None
                    with_ifaces = None
                    if isinstance(required_interfaces, dict):
                        required = required_interfaces.get(obj_key, None)
                    if isinstance(with_interfaces, dict):
                        with_ifaces = with_interfaces.get(obj_key, None)
                    sec_resource = secure(request, cls, id, required, with_ifaces)
                    #would be better to introspect the view functions signature here, thus allowing us to use args or kwargs
                    kwargs[obj_key] = sec_resource

                return f(request, *args, **kwargs)
            return g
        else:
            def g(request, *args, **kwargs):
                return f(request, *args, **kwargs)
            return g
    return decorator

Example 33

Project: PyClassLessons
Source File: common.py
View license
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.scheme,
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    pass
        return http.HttpResponsePermanentRedirect(newurl)

Example 34

Project: django-security
Source File: views.py
View license
@csrf_exempt
def csp_report(request, csp_save=False, csp_log=True):
    """
    .. _csp_report:

    Collect Content Security Policy reports from browsers. This view has
    two optional keyword arguments:

        ``csp_save``    if True, reports will be saved as ``CspReport`` objects
                        in database; this table is registered with Django
                        Admin, so they can be later viewed in admin console.

        ``csp_log``     if True, reports will be logged through Django logging
                        facility under ``security`` class

    By default only logging is enabled. To collect reports, this view needs to
    be added to project's urls.py. Examples:

    Default mode, only logger enable, no database logging:

        ``url(r'^csp-report/$', security.views.csp_report),``

    Logger and database enabled:

        ``url(r'^csp-report/$', security.views.csp_report,
        kwargs={'csp_save':True,'csp_log':True}),``
    """

    # http://www.w3.org/TR/CSP/#sample-violation-report
    if not request.method == 'POST':
        log.debug('Unexpect CSP report method %s', request.method)
        return HttpResponseForbidden()

    if (
        'CONTENT_TYPE' not in request.META
        or request.META['CONTENT_TYPE'] != 'application/json'
    ):
        log.debug('Missing CSP report Content-Type %s', request.META)
        return HttpResponseForbidden()

    try:
        csp_dict = json.loads(request.body)
    except ValueError:
        log.debug('Cannot JSON decode CSP report %s', request.body)
        return HttpResponseForbidden()

    if 'csp-report' not in csp_dict:
        log.debug('Invalid CSP report structure %s', csp_dict)
        return HttpResponseForbidden()

    report = csp_dict['csp-report']
    reporting_ip = request.META['REMOTE_ADDR']
    reporting_ua = request.META['HTTP_USER_AGENT']

    # log message about received CSP violation to Django log
    if csp_log:
        log.warn(
            'Content Security Policy violation: '
            '%s, reporting IP %s, user agent %s',
            report, reporting_ip, reporting_ua
        )

    # save received CSP violation to database
    if csp_save:
        csp_report = CspReport(
            document_uri=report.get('document-uri'),
            referrer=report.get('referrer'),
            blocked_uri=report.get('blocked-uri'),
            violated_directive=report.get('violated-directive'),
            original_policy=report.get('original-policy'),
            sender_ip=reporting_ip,
            user_agent=reporting_ua,
        )

        csp_report.save()

    # return 204 No Content to the client
    # per http://www.w3.org/TR/CSP/#report-uri
    # "Note: The user agent ignores the fetched resource"
    resp = HttpResponse()
    resp.status_code = 204

    return resp

Example 35

Project: django-bulbs
Source File: views.py
View license
@csrf_exempt
def targeting(request):
    if not (request.user and request.user.has_perm("ads.change_targetingoverride")):
        return HttpResponseForbidden(
            '{"detail": "You do not have permission to perform this action."}'
        )

    url = request.GET.get("url")
    if url is None:
        return HttpResponseNotFound()

    if url.startswith("http://") or url.startswith("https://"):
        parsed = urlparse(url)
        url = parsed.path

    try:
        view, args, kwargs = resolve(url)
    except Resolver404:
        return HttpResponseNotFound()

    req = RequestFactory().get(url)
    kwargs['request'] = req
    response = view(*args, **kwargs)
    if response.status_code != 200:
        return HttpResponseNotFound()

    targeting = response.context_data.get('targeting', {})

    if request.method == "POST":
        override_data = json.loads(request.body)
        for key, value in targeting.items():
            if value == override_data.get(key):
                del override_data[key]
        override, created = TargetingOverride.objects.get_or_create(url=url)
        override.targeting = override_data
        override.save()
        targeting.update(override_data)
    else:
        try:
            override = TargetingOverride.objects.get(url=url)
            targeting.update(override.targeting)
        except TargetingOverride.DoesNotExist:
            pass
    return HttpResponse(json.dumps(targeting), content_type="application/json")

Example 36

Project: wateronmars
Source File: views.py
View license
@loggedin_and_owner_required
@csrf_protect
@require_http_methods(["GET","POST"])
def user_river_source_item(request, owner_name, source_url):
  """Generate an editable view of a given source identified by its url."""
  owner_profile = request.owner_user.userprofile
  try:
    reference, form, form_data = prepare_reference_form(request, source_url,
                                                        owner_profile.sources)
  except Reference.DoesNotExist:
    return HttpResponseNotFound()
  except ValueError, e:
    return HttpResponseBadRequest(str(e))
  feedForms = {}
  for idx,feed in enumerate(WebFeed.objects.filter(source__url=source_url)):
    currentPrefix = "feed{0}".format(idx)
    initial = {"follow": feed in owner_profile.web_feeds.all()}
    followFieldName = currentPrefix+"-follow"
    if form_data:
      clean_checkbox_value(request, form_data[0], followFieldName, initial["follow"])
    feedForms[feed.xmlURL] = WebFeedOptInOutForm(request.owner_user,feed,
                                                 *form_data, error_class = CustomErrorList,
                                                 prefix=currentPrefix, initial=initial)
  def optOutFormsAreValid():
    return reduce(lambda currentValidity, nextForm: currentValidity and nextForm.is_valid(), feedForms.values(), True)
  def optOutFormsSave():
    return [f.save() for f in feedForms.values()]
  if request.POST:
    if settings.DEMO:
      return HttpResponseForbidden("Source editting is not possible in DEMO mode.")
    if form.is_valid() and optOutFormsAreValid():
      form.save()
      optOutFormsSave()
      return HttpResponseRedirect(reverse('wom_user.views.user_river_source_item',
                                          args=(request.user.username, source_url)))
  d = add_base_template_context_data(
    { 
      'ref_form': form,
      'feed_forms': feedForms,
      'ref_url': source_url,
      'ref_title': reference.title,
    },
    request.user.username,request.user.username)
  return render_to_response('source_edit.html',d,
                            context_instance=RequestContext(request))

Example 37

Project: ska
Source File: views.py
View license
def login(request):
    """Login.

    Authenticate with `ska` token into Django.

    :param django.http.HttpRequest request:
    :return django.http.HttpResponse:
    """
    user = authenticate(request=request)
    next_url = request.GET.get('next', None)

    if not next_url:
        if versions.DJANGO_GTE_1_7:
            request_data = request.GET
        else:
            request_data = request.REQUEST
        provider_data = get_provider_data(request_data)
        if provider_data:
            next_url = provider_data.get('REDIRECT_AFTER_LOGIN',
                                         REDIRECT_AFTER_LOGIN)

    if not next_url:
        next_url = '/'

    if user is not None:
        auth_login(request, user)
        name = user.first_name or user.username
        messages.info(request, _("Login succeeded. Welcome, {0}.").format(name))
        return HttpResponseRedirect(next_url)
    else:
        return HttpResponseForbidden(_("Authentication error!"))

Example 38

Project: wateronmars
Source File: views.py
View license
@check_and_set_owner
def user_river_sources(request,owner_name):
  if request.method == 'GET':
    owner_profile = request.owner_user.userprofile
    web_feeds = owner_profile.web_feeds.all()\
                                       .order_by('source__title')\
                                       .select_related("source")
    if request.user == request.owner_user:
      other_sources = owner_profile.sources.all()
    else:
      other_sources = owner_profile.public_sources.all()
    other_sources = other_sources.exclude(webfeed__userprofile=owner_profile)\
                                 .order_by("title")
    def add_tag_to_feed(feed):
      tag_names = get_item_tag_names(request.owner_user,feed)
      feed.main_tag_name = tag_names[0] if tag_names else ""
      return feed
    web_feeds = [add_tag_to_feed(f) for f in web_feeds.iterator()]
    web_feeds.sort(key=lambda f:f.main_tag_name)
    d = add_base_template_context_data({
        'tagged_web_feeds': web_feeds,
        'user_tags': get_user_tags(request.owner_user), 
        'other_sources': other_sources,
        'num_sources' : len(web_feeds)+other_sources.count(),
        'source_add_bookmarklet': generate_source_add_bookmarklet(
          request.build_absolute_uri("/"),request.user.username),
        }, request.user.username, owner_name)
    expectedFormat = request.GET.get("format","html")
    if expectedFormat.lower()=="opml":
      return render_to_response('sources_opml.xml',d,
                                context_instance=RequestContext(request),
                                mimetype="text/xml")
    else:
      return render_to_response('sources.html',d,
                                context_instance=RequestContext(request))
  elif request.user != request.owner_user:
    return HttpResponseForbidden()
  elif request.method == 'POST':
    try:
      src_info = simplejson.loads(request.body)
    except Exception:
      src_info = {}
    if not u"url" in src_info:
      return HttpResponseBadRequest("Only a JSON formatted request with a 'url' parameter is accepted.")
    q = QueryDict('', mutable=True)
    q.update(src_info)
    request.POST = q
    return user_river_source_add(request, owner_name)
  else:
    return HttpResponseNotAllowed(['GET','POST'])

Example 39

Project: GAE-Bulk-Mailer
Source File: common.py
View license
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.is_secure() and 'https' or 'http',
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    pass
        return http.HttpResponsePermanentRedirect(newurl)

Example 40

Project: django-frontendadmin
Source File: views.py
View license
def _get_instance(request, mode_name, app_label, model_name, instance_id=None,
                                            form=None,
                                            form_fields=None,
                                            form_exclude=None):
    '''
    Returns the model and an instance_form for the given arguments. If an primary
    key (instance_id) is given, it will return also the instance.

    If the user has no permission to add, change or delete the object, a
    HttpResponse is returned.
    '''
    # Check for permission to add/change/delete this object
    if not check_permission(request, mode_name, app_label, model_name):
        return HttpResponseForbidden('You have no permission to do this!')

    try:
        model = get_model(app_label, model_name)
    # Model does not exist
    except AttributeError:
        return HttpResponseForbidden('This model does not exist!')
    label = '%s.%s' % (app_label, model_name)
    # get form for model
    if label in FORMS and not form:
        form = import_function(FORMS[label])
    elif model in site._registry and not form:
        form = site._registry[model].form
    elif form is None:
        form = FrontendAdminModelForm
    
    if label in EXCLUDES:
        form_exclude = EXCLUDES[label]
    if label in FIELDS:
        form_fields = FIELDS[label]

    instance_form = modelform_factory(model, form=form,
                                      fields=form_fields, exclude=form_exclude)
    # if instance_id is set, grab this model object
    if instance_id:
        instance = model.objects.get(pk=instance_id)
        return model, instance_form, instance
    return model, instance_form

Example 41

Project: sublimall-server
Source File: views.py
View license
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        email = request.FILES.get('email')
        api_key = request.FILES.get('api_key')
        version = request.FILES.get('version')
        platform = request.FILES.get('platform')
        arch = request.FILES.get('arch')
        package_file = request.FILES.get('package')
        package_size = None

        if email:
            email = email.read()
        if api_key:
            api_key = api_key.read()
        if version:
            version = version.read()
        if platform:
            platform = platform.read()
        if arch:
            arch = arch.read()
        if package_file:
            package_size = package_file.seek(0, 2)
        if not email or not api_key or not package_size or not version:
            message = {'success': False, 'errors': []}
            if not email:
                message['errors'].append('Email is mandatory.')
            if not api_key:
                message['errors'].append('API key is mandatory.')
            if not version:
                message['errors'].append('Version is mandatory.')
            if not package_size:
                message['errors'].append('Package is mandatory.')
            return HttpResponseBadRequest(json.dumps(message))

        member = self.get_member(email, api_key)
        if member is None:
            return HttpResponseForbidden(
                json.dumps({'success': False, 'errors': ['Bad credentials.']}))
        if not member.is_active:
            return HttpResponseForbidden(
                json.dumps(
                    {'success': False, 'errors': ['Account not active.']}))

        try:
            version = int(version)
        except ValueError:
            return HttpResponseBadRequest(json.dumps({
                'success': False,
                'errors': ['Bad version. Must be 2 or 3.']}))

        if version not in [2, 3]:
            return HttpResponseBadRequest(json.dumps({
                'success': False,
                'errors': ['Bad version. Must be 2 or 3.']}))

        package = Package(
            member=member,
            version=version,
            platform=platform,
            arch=arch,
            package=package_file)

        try:
            package.full_clean()
        except ValidationError as err:
            return HttpResponseBadRequest(
                json.dumps({'success': False, 'errors': err.messages}))

        package.save()
        # Cleanup old packages
        old_packages = member.package_set.filter(
            version=version).exclude(pk=package.pk)
        for old_package in old_packages:
            old_package.delete()
        return HttpResponse(json.dumps({'success': True}), status=201)

Example 42

Project: sublimall-server
Source File: views.py
View license
    def post(self, request, *args, **kwargs):
        email = request.POST.get('email')
        api_key = request.POST.get('api_key')
        version = request.POST.get('version')
        package_id = request.POST.get('package_id')

        if not email or not api_key and not version:
            message = {'success': False, 'errors': []}
            if not email:
                message['errors'].append('Email is mandatory.')
            if not api_key:
                message['errors'].append('API key is mandatory.')
            if not version:
                message['errors'].append('Version is mandatory.')
            return HttpResponseBadRequest(json.dumps(message))

        member = self.get_member(email, api_key)
        if member is None:
            return HttpResponseForbidden(
                json.dumps({'success': False, 'errors': ['Bad credentials.']}))
        if not member.is_active:
            return HttpResponseForbidden(
                json.dumps(
                    {'success': False, 'errors': ['Account not active.']}))
        if package_id and not member.package_set.get(pk=package_id):
            return HttpResponseForbidden(
                json.dumps(
                    {
                        'success': False,
                        'errors': ['Access to this package is not allowed.']}))

        try:
            if package_id:
                package = member.package_set.only('package').get(pk=package_id)
            else:
                package = member.package_set.filter(
                    version=version).only('package').latest('update')
        except Package.DoesNotExist:
            return HttpResponseNotFound(
                json.dumps(
                    {'success': False, 'errors': ['Package not found.']}))

        response = HttpResponse(
            package.package.read(),
            content_type='application/zip, application/octet-stream')
        response.streaming = True
        response['Content-Disposition'] = (
            'attachment; filename=package_version-%s.zip' % package.version)
        return response

Example 43

Project: django-wakawaka
Source File: views.py
View license
def edit(request, slug, rev_id=None, template_name='wakawaka/edit.html',
         extra_context=None, wiki_page_form=WikiPageForm,
         wiki_delete_form=DeleteWikiPageForm):
    """
    Displays the form for editing and deleting a page.
    """
    if extra_context is None:
        extra_context = {}

    # Get the page for slug and get a specific revision, if given
    try:
        queryset = WikiPage.objects.all()
        page = queryset.get(slug=slug)
        rev = page.current
        initial = {'content': page.current.content}

        # Do not allow editing wiki pages if the user has no permission
        if not request.user.has_perms(('wakawaka.change_wikipage', 'wakawaka.change_revision' )):
            return HttpResponseForbidden(ugettext('You don\'t have permission to edit pages.'))

        if rev_id:
            # There is a specific revision, fetch this
            rev_specific = Revision.objects.get(pk=rev_id)
            if rev.pk != rev_specific.pk:
                rev = rev_specific
                rev.is_not_current = True
                initial = {'content': rev.content, 'message': _('Reverted to "%s"' % rev.message)}


    # This page does not exist, create a dummy page
    # Note that it's not saved here
    except WikiPage.DoesNotExist:
        
        # Do not allow adding wiki pages if the user has no permission
        if not request.user.has_perms(('wakawaka.add_wikipage', 'wakawaka.add_revision',)):
            return HttpResponseForbidden(ugettext('You don\'t have permission to add wiki pages.'))

        page = WikiPage(slug=slug)
        page.is_initial = True
        rev = None
        initial = {'content': _('Describe your new page %s here...' % slug),
                   'message': _('Initial revision')}

    # Don't display the delete form if the user has nor permission
    delete_form = None
    # The user has permission, then do
    if request.user.has_perm('wakawaka.delete_wikipage') or \
       request.user.has_perm('wakawaka.delete_revision'):
        delete_form = wiki_delete_form(request)
        if request.method == 'POST' and request.POST.get('delete'):
            delete_form = wiki_delete_form(request, request.POST)
            if delete_form.is_valid():
                return delete_form.delete_wiki(request, page, rev)

    # Page add/edit form
    form = wiki_page_form(initial=initial)
    if request.method == 'POST':
        form = wiki_page_form(data=request.POST)
        if form.is_valid():
            # Check if the content is changed, except there is a rev_id and the
            # user possibly only reverted the HEAD to it
            if not rev_id and initial['content'] == form.cleaned_data['content']:
                form.errors['content'] = (_('You have made no changes!'),)

            # Save the form and redirect to the page view
            else:
                try:
                    # Check that the page already exist
                    queryset = WikiPage.objects.all()
                    page = queryset.get(slug=slug)
                except WikiPage.DoesNotExist:
                    # Must be a new one, create that page
                    page = WikiPage(slug=slug)
                    page.save()

                form.save(request, page)
                
                kwargs = {
                    'slug': page.slug,
                }
                
                redirect_to = reverse('wakawaka_page', kwargs=kwargs)
                messages.success(request, ugettext('Your changes to %s were saved' % page.slug))
                return HttpResponseRedirect(redirect_to)

    template_context = {
        'form': form,
        'delete_form': delete_form,
        'page': page,
        'rev': rev,
    }
    template_context.update(extra_context)
    return render_to_response(template_name, template_context,
                              RequestContext(request))

Example 44

Project: transifex
Source File: views.py
View license
def add_permission_or_request(request, obj, view_name, approved=False,
                   template_name = 'authority/permission_form.html',
                   extra_context={}):
    """
    View for adding either a permission or a permission request for a user.

    This view is a centralized place for adding permissions/requests for any
    kind of object through the whole Transifex.

    Following the upstream django-authority app, all the entries are considered
    requests until the field approved be set to True.

    For the extra_context, this view expect a key called 'notice' that MUST
    have a determinate dictionary structure to be able to send notifications
    and save action logs. See the `_send_notice_save_action` function docstring
    for more information.

    Example of `extra_context` with `notice` key:
        # See `_send_notice_save_action` docstring for the `notice` var below
        notice = {}
        extra_context.update({'notice': notice})

    If the key 'notice' is not found in the extra_context parameter, nothing is
    executed about notification and action log.
    """
    codename = request.POST.get('codename', None)
    next = get_next(request, obj)

    if request.method == 'POST':
        # POST method requires a permission codename
        if codename is None:
            return HttpResponseForbidden(next)
        form = UserAjaxPermissionForm(data=request.POST, obj=obj,
                                  approved=approved, perm=codename,
                                  initial=dict(codename=codename))
        if not approved:
            # Limit permission request to current user
            form.data['user'] = request.user
        if form.is_valid():
            permission = form.save(request)

            if extra_context.has_key('notice'):
                # ActionLog & Notification
                _send_notice_save_action(request, extra_context['notice'])

            if approved:
                msg = _('You added a permission.')
            else:
                msg = _('You added a permission request.')

            messages.info(request, msg)

            return HttpResponseRedirect(next)
    else:
        form = None

    context = {
        'form': form,
        'form_url': txurl_for_obj(view_name, obj),
        'next': next,
        'perm': codename,
        'approved': approved,
    }
    extra_context.update({'notice':None})
    context.update(extra_context)
    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))

Example 45

View license
@rollback_on_exception
def calculate_and_get_json_for_api(request, username, sheet_id):
    sheet = get_object_or_404(Sheet, pk=sheet_id, owner__username=username)
    pads = None

    if request.method == 'POST':
        params = request.POST
    else:
        params = request.GET

    if 'api_key' in params:
        if not sheet.allow_json_api_access:
            transaction.rollback()
            return HttpResponseForbidden()
        elif params['api_key'] != sheet.api_key:
            transaction.rollback()
            return HttpResponseForbidden()
    elif 'dirigible_l337_private_key' in params:
        pads = OneTimePad.objects.filter(
            user=sheet.owner,
            guid=params['dirigible_l337_private_key']
        )
        too_old = datetime.now() - timedelta(36000)
        if len(pads) != 1 or pads[0].creation_time < too_old:
            transaction.rollback()
            return HttpResponseForbidden()
    else:
        transaction.rollback()
        return HttpResponseForbidden()

    worksheet = sheet.unjsonify_worksheet()
    for encoded_loc, new_formula in params.items():
        colrow = cell_ref_as_string_to_coordinates(encoded_loc)
        if colrow is not None:
            col, row = colrow
            worksheet.set_cell_formula(col, row, new_formula)
    sheet.jsonify_worksheet(worksheet)

    try:
        sheet.calculate()
        worksheet = sheet.unjsonify_worksheet()
        if worksheet._usercode_error:
            return HttpResponse(json.dumps({
                "usercode_error": {
                    "message": worksheet._usercode_error["message"],
                    "line": str(worksheet._usercode_error["line"])
                }
            }))
        response = HttpResponse(
            _sheet_to_value_only_json(sheet.name, worksheet))
        response['Access-Control-Allow-Origin'] = '*'
        return response
    except (Exception, HTTPError), e:
        return HttpResponse(str(e))
    finally:
        transaction.commit()

Example 46

Project: coursys
Source File: views.py
View license
@requires_course_by_slug
@transaction.atomic
def submit(request, course_slug):
    person = get_object_or_404(Person,userid=request.user.username)
    course = get_object_or_404(CourseOffering, slug = course_slug)
    member = Member.objects.exclude(role='DROP').get(person=person, offering=course)
    error_info=None
    name = request.POST.get('GroupName')
    if name:
        name = name[:30]
    #Check if group has a unique name
    if Group.objects.filter(name=name,courseoffering=course):
        error_info="A group named \"%s\" already exists" % (name)
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
    #Check if the group name is empty, these two checks may need to be moved to forms later.
    if name == "":
        error_info = "Group name cannot be empty: please enter a group name."
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
    

    else:
        # find selected activities
        selected_act = []
        activities = Activity.objects.filter(offering=course, group=True, deleted=False)
        if not is_course_staff_by_slug(request, course_slug):
            activities = activities.exclude(status='INVI')

        for activity in activities:
            activityForm = ActivityForm(request.POST, prefix=activity.slug)
            if activityForm.is_valid() and activityForm.cleaned_data['selected'] == True:
                selected_act.append(activity)
        
        # no selected activities: fail.
        if not selected_act:
            messages.add_message(request, messages.ERROR, "Group not created: no activities selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        
        #groupForSemesterForm = GroupForSemesterForm(request.POST)
        #if groupForSemesterForm.is_valid():
        #    groupForSemester = groupForSemesterForm.cleaned_data['selected']
        groupForSemester = False
        
        #validate database integrity before saving anything. 
        #If one student is in a group for an activity, he/she cannot be in another group for the same activity.
        if is_course_student_by_slug(request, course_slug):
            isStudentCreatedGroup = True
            studentList = []
            studentList.append(member)
        elif is_course_staff_by_slug(request, course_slug):
            isStudentCreatedGroup = False
            studentList = []
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
                    studentList.append(student)
        #Check if students has already in a group
        if _validateIntegrity(request,isStudentCreatedGroup, groupForSemester, course, studentList, selected_act) == False:
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        #No selected members,group creating will fail.        
        if not studentList:
            messages.add_message(request, messages.ERROR, "Group not created: no members selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        
        group = Group(name=name, manager=member, courseoffering=course, groupForSemester = groupForSemester)
        group.save()
        #LOG EVENT#
        l = LogEntry(userid=request.user.username,
        description="created a new group %s for %s." % (group.name, course),
        related_object=group )
        l.save()

        if is_course_student_by_slug(request, course_slug):
            for activity in selected_act:
                groupMember = GroupMember(group=group, student=member, confirmed=True, activity_id=activity.id)
                groupMember.save()
                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                description="automatically became a group member of %s for activity %s." % (group.name, groupMember.activity),
                    related_object=groupMember )
                l.save()

            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))

        elif is_course_staff_by_slug(request, course_slug):
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
                    for activity in selected_act:
                        groupMember = GroupMember(group=group, student=student, confirmed=True, activity_id=activity.id)
                        groupMember.save()
                        #LOG EVENT#
                        l = LogEntry(userid=request.user.username,
                        description="added %s as a group member to %s for activity %s." % (student.person.userid,group.name, groupMember.activity),
                            related_object=groupMember )
                        l.save()
                    
                    n = NewsItem(user=student.person, author=member.person, course=group.courseoffering,
                     source_app="group", title="Added to Group",
                     content="You have been added the group %s." % (group.name),
                     url=reverse('groups.views.groupmanage', kwargs={'course_slug':course.slug})
                    )
                    n.save()
                    
            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
        else:
            return HttpResponseForbidden()

Example 47

Project: uwsgi.it
Source File: views.py
View license
@need_basicauth
@csrf_exempt
def container(request, id):
    customer = request.user.customer
    try:
        container = customer.container_set.get(pk=(int(id) - UWSGI_IT_BASE_UID))
    except:
        return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
    if request.method == 'POST':
        response = check_body(request)
        if response:
            return response
        allowed_keys = (
            'name', 'note', 'quota_threshold', 'jid', 'jid_secret',
            'jid_destinations', 'nofollow', 'pushover_user',
            'pushover_token', 'pushover_sound', 'alarm_freq',
            'pushbullet_token', 'slack_webhook',
            'custom_distros_storage',
        )

        j = json.loads(request.read())
        if not j:
            return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
        for key in j:
            if key in allowed_keys:
                setattr(container, key, j[key])
        if 'ssh_keys' in j:
            container.ssh_keys_raw = '\n'.join(j['ssh_keys'])
            container.ssh_keys_mtime = datetime.datetime.now()
        if 'distro' in j:
            container.distro = Distro.objects.get(pk=j['distro'])
        if 'custom_distro' in j:
            container.custom_distro = CustomDistro.objects.filter(pk=j['custom_distro'], container__server=container.server, container__customer=customer).exclude(container=container)[0]
        if 'memory' in j:
            if container.server.owner == customer:
                container.memory = int(j['memory'])
        if 'storage' in j:
            if container.server.owner == customer:
                container.storage = int(j['storage'])
        if 'tags' in j:
            new_tags = []
            for tag in j['tags']:
                try:
                    new_tags.append(Tag.objects.get(customer=customer, name=tag))
                except:
                    pass
            container.tags = new_tags
        # linking and unlinking requires reboot
        if 'link' in j:
            try:
                link = ContainerLink()
                link.container = container
                link.to = Container.objects.get(pk=(int(j['link']) - UWSGI_IT_BASE_UID))
                link.full_clean()
                link.save()
                container.last_reboot = datetime.datetime.now()
            except:
                response = HttpResponse(json.dumps({'error': 'Conflict'}), content_type="application/json")
                response.status_code = 409
                return response
        if 'unlink' in j:
            try:
                link = container.containerlink_set.get(to=(int(j['unlink']) - UWSGI_IT_BASE_UID))
                link.delete()
                container.last_reboot = datetime.datetime.now()
            except:
                response = HttpResponse(json.dumps({'error': 'Conflict'}), content_type="application/json")
                response.status_code = 409
                return response
        if 'reboot' in j:
            container.last_reboot = datetime.datetime.now()
        container.full_clean()
        container.save()
    c = {
        'uid': container.uid,
        'name': container.name,
        'hostname': container.hostname,
        'ip': str(container.ip),
        'memory': container.memory,
        'storage': container.storage,
        'uuid': container.uuid,
        'distro': None,
        'distro_name': None,
        'server': container.server.name,
        'server_address': container.server.address,
        'jid': container.jid,
        'jid_destinations': container.jid_destinations,
        'pushover_user': container.pushover_user,
        'pushover_token': container.pushover_token,
        'pushover_sound': container.pushover_sound,
        'pushbullet_token': container.pushbullet_token,
        'slack_webhook': container.slack_webhook,
        'alarm_freq': container.alarm_freq,
        'quota_threshold': container.quota_threshold,
        'nofollow': container.nofollow,
        'note': container.note,
        'linked_to': container.linked_to,
        'custom_distros_storage': container.custom_distros_storage,
        'custom_distro': None,
        'ssh_keys': container.ssh_keys,
        'tags': [t.name for t in container.tags.all()],
        'legion_address': [l.address for l in container.server.legion_set.all()]
    }
    if container.distro:
        c['distro'] = container.distro.pk
        c['distro_name'] = container.distro.name
    if container.custom_distro:
        c['custom_distro'] = container.custom_distro.pk
        c['custom_distro_name'] = container.custom_distro.name
    return spit_json(request, c)

Example 48

Project: uwsgi.it
Source File: views.py
View license
@need_basicauth
@csrf_exempt
def containers(request):
    if request.method == 'POST':
        response = check_body(request)
        if response:
            return response
        j = json.loads(request.read())
        needed_keys = ('server', 'name', 'memory', 'storage')
        for k in needed_keys:
            if not k in j.keys():
                return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
        try:
            server = Server.objects.get(address=j['server'])
            if server.owner != request.user.customer:
                return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
        except:
            return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
        if int(j['memory']) > server.free_memory or int(j['memory']) <= 0:
            return HttpResponse(json.dumps({'error': 'Conflict', 'reason':'not enough memory'}), content_type="application/json")
        if int(j['storage']) > server.free_storage or int(j['storage']) <= 0:
            return HttpResponse(json.dumps({'error': 'Conflict', 'reason':'not enough storage'}), content_type="application/json")
        try:
            container = Container(customer=request.user.customer, server=server)
            container.name = j['name']
            container.memory = int(j['memory'])
            container.storage = int(j['storage'])
            container.save()
            response = HttpResponse(json.dumps({'message': 'Created'}), content_type="application/json")
            response.status_code = 201
            return response
        except:
            response = HttpResponse(json.dumps({'error': 'Conflict'}), content_type="application/json")
            response.status_code = 409
            return response
    elif (request.method == 'GET' and
         'tags' in request.GET):
            containers = request.user.customer.container_set.filter(tags__name__in=request.GET['tags'].split(','))
    else:
        containers = request.user.customer.container_set.all()

    c = []
    for container in containers:
        cc = {
            'uid': container.uid,
            'name': container.name,
            'hostname': container.hostname,
            'ip': str(container.ip),
            'memory': container.memory,
            'storage': container.storage,
            'uuid': container.uuid,
            'distro': None,
            'distro_name': None,
            'custom_distro': None,
            'custom_distro_name': None,
            'server': container.server.name,
            'server_address': container.server.address,
            'tags': [t.name for t in container.tags.all()]
        }
        if container.distro:
            cc['distro'] = container.distro.pk
            cc['distro_name'] = container.distro.name
        if container.custom_distro:
            cc['custom_distro'] = container.custom_distro.pk
            cc['custom_distro_name'] = container.custom_distro.name
        c.append(cc)

    return spit_json(request, c)

Example 49

Project: coursys
Source File: views.py
View license
@login_required
@transaction.atomic
def remove_student(request, course_slug, group_slug):
    course = get_object_or_404(CourseOffering, slug = course_slug)
    group = get_object_or_404(Group, courseoffering = course, slug = group_slug)
    members = GroupMember.objects.filter(group = group).select_related('group', 'student', 'student__person', 'activity')

    # check permissions
    if is_course_staff_by_slug(request, course_slug):
        is_staff = True
    elif is_course_student_by_slug(request, course_slug):
        is_staff = False
        memberships = [m for m in members if m.student.person.userid == request.user.username]
        if not memberships:
            # student must be in this group
            return HttpResponseForbidden()
    else:
        return HttpResponseForbidden()

    if request.method == "POST":
        for m in members:
            f = StudentForm(request.POST, prefix=unicode(m.student.person.userid_or_emplid()) + '_' + m.activity.slug)
            if (is_staff or m.student_editable(request.user.username)=="") \
                and f.is_valid() and f.cleaned_data['selected'] == True:
            
                m.delete()

                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                description="deleted %s in group %s for %s." % (m.student.person.userid, group.name, m.activity),
                related_object=m.group)
                l.save()

        if is_staff:
            return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
        else:
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))

    else:
        data = []
        for m in members:
            editable = m.student_editable(request.user.username)
            if is_staff or editable == "":
                f = StudentForm(prefix=unicode(m.student.person.userid_or_emplid()) + '_' + m.activity.slug)
                data.append({'form': f, 'member': m})
            else:
                data.append({'form': None, 'member': m, 'reason': editable})

        return render_to_response('groups/remove_student.html', \
                          {'course':course, 'group' : group, 'data':data, 'is_staff':is_staff}, \
                          context_instance = RequestContext(request))

Example 50

Project: uwsgi.it
Source File: views.py
View license
@need_basicauth
@csrf_exempt
def alarms(request):
    query = {}
    if 'container' in request.GET:
        try:
            query['container'] = request.user.customer.container_set.get(pk=(int(request.GET['container']) - UWSGI_IT_BASE_UID))
        except:
            return HttpResponseForbidden(json.dumps({'error': 'Forbidden'}), content_type="application/json")
    else:
        query['container__in'] = request.user.customer.container_set.all()

    if 'vassal' in request.GET:
        query['vassal'] = request.GET['vassal']

    if 'class' in request.GET:
        query['_class'] = request.GET['class']

    if 'color' in request.GET:
        query['color'] = request.GET['color']

    if 'level' in request.GET:
        query['level'] = int(request.GET['level'])

    if 'line' in request.GET:
        query['line'] = int(request.GET['line'])

    if 'filename' in request.GET:
        query['filename'] = request.GET['filename']

    if 'func' in request.GET:
        query['func'] = request.GET['func']

    alarms = Alarm.objects.filter(**query)

    a = []

    if 'with_total' in request.GET:
        response = {'total': alarms.count(), 'alarms': a}
    else:
        response = a

    if 'range' in request.GET:
        to = request.GET['range']
        try:
            if '-' in to:
                _from, to = to.split('-')
            else:
                _from = 0
            alarms = alarms[int(min(_from, to)):int(max(_from, to))]

        except:
            response = HttpResponse(json.dumps({'error': 'Requested Range Not Satisfiable'}), content_type="application/json")
            response.status_code = 416
            return response
        if _from > to:
            alarms = alarms.reverse()

    for alarm in alarms:
        aa = {
            'id': alarm.pk,
            'container': alarm.container.uid,
            'level': alarm.level,
            'color': alarm.color,
            'class': alarm._class,
            'vassal': alarm.vassal,
            'line': alarm.line,
            'filename': alarm.filename,
            'func': alarm.func,
            'unix': int(alarm.unix.strftime('%s')),
            'msg': alarm.msg
        }
        a.append(aa)

    return spit_json(request, response)