Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
499394
def permission_denied(request, template_name='403.html'):
    

    response = render_in_page(request, template_name)

    if response:
        return response

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(template.render(RequestContext(request)))
1133481
def _call(self, path, method, body=None, headers=None):
        
        try:
            resp = self.http.do_call(path, method, body, headers)
        except http.HTTPError as err:
            if err.status == 401:
                raise PermissionError('Insufficient permissions to query ' +
                    '%s with user %s :%s' % (path, self.user, err))
            raise
        return resp
847491
def render_404_public_file!(file_name)
      four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir)
      return unless File.file?(four_oh_four_path)
      send_file four_oh_four_path, status: 404
    end
732425
public Template handleRequest (HttpServletRequest req, HttpServletResponse rsp, Context ctx)
        throws Exception
    {
        InvocationContext ictx = (InvocationContext)ctx;
        Logic logic = null;

        // listen for exceptions so that we can report them
        EventCartridge ec = ictx.getEventCartridge();
        if (ec == null) {
            ec = new EventCartridge();
            ec.attachToContext(ictx);
            ec.addEventHandler(this);
        }

        // if our application failed to initialize, fail with a 500 response
        if (_app == null) {
            rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // obtain the siteid for this request and stuff that into the context
        int siteId = SiteIdentifier.DEFAULT_SITE_ID;
        SiteIdentifier ident = _app.getSiteIdentifier();
        if (ident != null) {
            siteId = ident.identifySite(req);
        }
        if (_usingSiteLoading) {
            ctx.put("__siteid__", Integer.valueOf(siteId));
        }

        // put the context path in the context as well to make it easier to
        // construct full paths
        ctx.put("context_path", req.getContextPath());

        // then select the template
        Template tmpl = null;
        try {
            tmpl = selectTemplate(siteId, ictx);
        } catch (ResourceNotFoundException rnfe) {
            // send up a 404.  For some annoying reason, Jetty tells Apache
            // that all is okay (200) when sending its own custom error pages,
            // forcing us to use Jetty's custom error page handling code rather
            // than passing it up the chain to be dealt with appropriately.
            rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }

        // assume the request is in the default character set unless it has
        // actually been sensibly supplied by the browser
        if (req.getCharacterEncoding() == null) {
            req.setCharacterEncoding(_charset);
        }

        // assume an HTML response in the default character set unless
        // otherwise massaged by the logic
        rsp.setContentType("text/html; charset=" + _charset);

        Exception error = null;
        try {
            // insert the application into the context in case the logic or a
            // tool wishes to make use of it
            ictx.put(APPLICATION_KEY, _app);

            // if the application provides a message manager, we want create a
            // translation tool and stuff that into the context
            MessageManager msgmgr = _app.getMessageManager();
            if (msgmgr != null) {
                I18nTool i18n = new I18nTool(req, msgmgr);
                ictx.put(I18NTOOL_KEY, i18n);
            }

            // create a form tool for use by the template
            FormTool form = new FormTool(req);
            ictx.put(FORMTOOL_KEY, form);

            // create a new string tool for use by the template
            StringTool string = new StringTool();
            ictx.put(STRINGTOOL_KEY, string);

            // create a new data tool for use by the tempate
            DataTool datatool = new DataTool();
            ictx.put(DATATOOL_KEY, datatool);

            // create a curreny tool set up to use the correct locale
            CurrencyTool ctool = new CurrencyTool(req.getLocale());
            ictx.put(CURRENCYTOOL_KEY, ctool);

            // allow the application to prepare the context
            _app.prepareContext(ictx);

            // allow the application to do global access control
            _app.checkAccess(ictx);

            // resolve the appropriate logic class for this URI and execute it
            // if it exists
            String path = req.getServletPath();
            logic = resolveLogic(path);
            if (logic != null) {
                logic.invoke(_app, ictx);
            }

        } catch (Exception e) {
            error = e;
        }

        // if an error occurred processing the template, allow the application
        // to convert it to something more appropriate and then handle it
        String errmsg = null;
        try {
            if (error != null) {
                throw _app.translateException(error);
            }

        } catch (RedirectException re) {
            rsp.sendRedirect(re.getRedirectURL());
            return null;

        } catch (HttpErrorException hee) {
            String msg = hee.getErrorMessage();
            if (msg != null) {
                rsp.sendError(hee.getErrorCode(), msg);
            } else {
                rsp.sendError(hee.getErrorCode());
            }
            return null;

        } catch (FriendlyException fe) {
            // grab the error message, we'll deal with it shortly
            errmsg = fe.getMessage();

        } catch (Exception e) {
            errmsg = _app.handleException(req, logic, e);
        }

        // if we have an error message, insert it into the template
        if (errmsg != null) {
            // try using the application to localize the error message
            // before we insert it
            MessageManager msgmgr = _app.getMessageManager();
            if (msgmgr != null) {
                errmsg = msgmgr.getMessage(req, errmsg);
            }
            ictx.put(ERROR_KEY, errmsg);
        }

        return tmpl;
    }
132799
def bad_request(request, template_name='400.html'):
    

    response = render_in_page(request, template_name)

    if response:
        return response

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    return http.HttpResponseBadRequest(template.render(Context({})))
901007
def http_method_not_allowed(self, *args, **kwargs):
        
        resp = super(JsonResponseMixin, self).http_method_not_allowed(*args, **kwargs)
        resp['Content-Type'] = 'application/json'

        return resp
621859
def permitted_to? (privilege, options = {}, &block)
      options = {
        :user =>  Authorization.current_user,
        :object => self
      }.merge(options)
      Authorization::Engine.instance.permit?(privilege,
          {:user => options[:user],
           :object => options[:object]},
          &block)
    end
490404
def html(self, data=None, template=None):
        
        if data is None:
            data = {}
        if template:
            return render(self.request, template, data)
        return HttpResponse(data)
293304
def handle_not_allowed(environ, start_response):
    
    _methods = util.wsgi_path_item(environ, '_methods')
    headers = {}
    if _methods:
        headers['allow'] = str(_methods)
    raise webob.exc.HTTPMethodNotAllowed(
        ('The method specified is not allowed for this resource.'),
        headers=headers, json_formatter=util.json_error_formatter)
597004
def render(self, request, context, status=codes.ok, content_type=None,
            args=None, kwargs=None):
        ""

        if isinstance(self.template_name, (list, tuple)):
            template = loader.select_template(self.template_name)
        elif self.template_name:
            template = loader.get_template(self.template_name)
        else:
            template = loader.Template(self.template_string)

        context = RequestContext(request, context)
        content = template.render(context)

        return HttpResponse(content, status=status, content_type=content_type)
805367
def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,
content=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):
    
    return AccessFailedResponse(request, template, content, content_type, status=401)
1089404
def has_permission(self, request, view):
        
        url_username = request.parser_context.get('kwargs', {}).get('username', '')
        if request.user.username.lower() != url_username.lower():
            if request.user.is_staff:
                return False  # staff gets 403
            raise Http404()
        return True
871830
def handler500(request):
    
    from django.template import Context, loader
    from django.http import HttpResponseServerError
    from overseer.context_processors import default
    import logging
    import sys
    try:
        context = default(request)
    except Exception, e:
        logging.error(e, exc_info=sys.exc_info(), extra={'request': request})
        context = {}
    
    context['request'] = request
    
    t = loader.get_template('500.html') # You need to create a 500.html template.
    return HttpResponseServerError(t.render(Context(context)))
821336
def permission_required_raise(perm, login_url=None, raise_exception=True):
    
    return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
1200152
def error(response)
      log.info "Parsing response as error..."

      case response['Content-Type']
      when /json/
        log.debug "Detected error response as JSON"
        log.debug "Parsing error response as JSON"
        message = JSON.parse(response.body)
      else
        log.debug "Detected response as text/plain"
        message = response.body
      end

      case response.code.to_i
      when 400
        raise Error::HTTPBadRequest.new(message: message)
      when 401
        raise Error::HTTPUnauthorizedRequest.new(message: message)
      when 403
        raise Error::HTTPForbiddenRequest.new(message: message)
      when 404
        raise Error::HTTPNotFound.new(message: message)
      when 405
        raise Error::HTTPMethodNotAllowed.new(message: message)
      when 406
        raise Error::HTTPNotAcceptable.new(message: message)
      when 504
        raise Error::HTTPGatewayTimeout.new(message: message)
      when 500..600
        raise Error::HTTPServerUnavailable.new
      else
        raise "I got an error #{response.code} that I don't know how to handle!"
      end
    end
860521
def _handle_http_errors(response):
    
    code = response.status_code
    if 200 <= code < 400:
        return response
    elif code in (403, 404):
        raise {403: _ObjectPermissionError,
               404: _ObjectNotFoundError}[code](response.reason)
    response.raise_for_status()
169981
def run(self, value, errors, request):
        """"""
        thing = super(AccessibleDBThing, self).run(value, errors, request)
        if errors:
            return None
        if not thing.can_access(request.user):
            message = 'Insufficient permissions for {0}'.format(self.param)
            raise HTTPForbidden(message)
        return thing