checks that an authorization call has been made during the request
436601
def check_authorization(self, response):
        """"""
        if not hasattr(request, '_authorized'):
            raise Unauthorized
        elif not request._authorized:
            raise Unauthorized
        return response
123308
def _apicall(self, method, **params):
        """"""
        LOGGER.debug('%s(%r)', method, params)
        auth = {
            'customernumber': self._get_provider_option('auth_customer_id'),
            'apikey': self._get_provider_option('auth_api_key'),
        }
        if method == 'login':
            auth['apipassword'] = self._get_provider_option('auth_api_password')
        else:
            auth['apisessionid'] = self.api_session_id
        if not all(auth.values()):
            raise Exception('No valid authentication mechanism found')
        data = self._request('POST', url='', data={
            'action': method,
            'param': dict(params, **auth),
        })
        if data['status'] != 'success':
            raise Exception("{} ({})".format(
                data['longmessage'], data['statuscode']))
        return data.get('responsedata', {})
525987
def perform_authorization(self):
        

        for permission in self.permissions:
            if not permission.has_permission():
                if request.user:
                    raise errors.PermissionDenied()
                else:
                    raise errors.NotAuthenticated()
169975
def requires_auth(self, func):
        '''
        
        '''
        @wraps(func)
        def decorated(*args, **kwargs):
            ''' Wrapper '''
            auth = request.authorization
            if not auth or not self.check_auth(auth.username, auth.password):
                return self.authenticate()
            return func(*args, **kwargs)
        return decorated
991120
def CheckClientApprovalRequest(approval_request):
  """"""

  _CheckExpired(approval_request)
  _CheckHasEnoughGrants(approval_request)

  if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive():
    return True

  token = access_control.ACLToken(username=approval_request.requestor_username)
  approvers = set(g.grantor_username for g in approval_request.grants)

  labels = sorted(
      data_store.REL_DB.ReadClientLabels(approval_request.subject_id),
      key=lambda l: l.name)
  for label in labels:
    client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.CheckApproversForLabel(
        token, rdfvalue.RDFURN(approval_request.subject_id),
        approval_request.requestor_username, approvers, label.name)

  return True
77543
def check_auth(func):
    
    def wrapper(handler, *args, **kwargs):
        if handler.check_auth_header():
            return func(handler, *args, **kwargs)
    return wrapper
748506
private Access authorizationCheck(final HttpServletRequest req, Action action)
  {
    return IndexTaskUtils.datasourceAuthorizationCheck(req, action, task.getDataSource(), authorizerMapper);
  }
429425
function handleUnauthorizedAPIResponse(error) {
    const response = error && error.response;
    const errorStatus = response && response.status;
    const requestUrl = response && response.config && response.config.url;
    const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint;

    switch (errorStatus) { // eslint-disable-line default-case
      case 401:
        if (requestIsTokenRefresh) {
          logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`);
        } else {
          logInfo(`Unauthorized API response from ${requestUrl}`);
        }
        break;
      case 403:
        logInfo(`Forbidden API response from ${requestUrl}`);
        break;
    }

    return Promise.reject(error);
  }
828238
function onUnauthorizedAccess() {
          if (angular.isFunction(permission.onUnauthorized)) {
            permission.onUnauthorized()($element);
          } else {
            var onUnauthorizedMethodName = $permission.defaultOnUnauthorizedMethod;
            PermPermissionStrategies[onUnauthorizedMethodName]($element);
          }
        }
835392
def endpoint(f):
    """"""

    def check_authentication(self, **kwargs):
        """If the `authentication` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 401 authentication error"""
        if getattr(self, 'authentication', None) is None:
            current_app.logger.debug("No authentication method")
            return

        a = self.authentication()
        if not hasattr(a, 'is_authenticated'):
            current_app.logger.debug("No is_authenticated method")
            return

        if not a.is_authenticated(**kwargs):
            msg = getattr(g, 'authentication_error', 'Authentication failed')
            current_app.logger.warning("Authentication failed: {}".format(msg))
            return self._make_response(401, msg, abort=True)
        current_app.logger.debug("Authentication successful")

    def check_authorization(self):
        """If the `authorization` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 403 authorization error"""
        current_app.logger.info("Checking authentication/authorization")
        auth_class = getattr(self, 'authorization',
                             getattr(self, 'authentication', None))
        if auth_class is None:
            current_app.logger.debug("No authorization class")
            return

        a = auth_class()
        if not hasattr(a, 'is_authorized'):
            current_app.logger.debug("No is_authorized method")
            return

        if not a.is_authorized(record=g._resource_instance):
            current_app.logger.warning("Authorization failed")
            return self._make_response(403, "Authorization failed", abort=True)
        current_app.logger.debug("Authorization successful")

    def validate_request(self, **kwargs):
        """Call the validator class and validate the request_data. This method
           returns True or False. On False, a 400 will be returned with the
           reasons for the validation error. On True, the operation will
           continue."""
        current_app.logger.info(
            "Checking {} validation".format(request.method))
        if getattr(self, 'validation', None) is None:
            current_app.logger.warning("No validation specified")
            return

        v = self.validation()
        method = 'validate_{}'.format(request.method.lower())

        if not hasattr(v, method):
            current_app.logger.warning("No validation method specified")
            return
        errors = getattr(v, method)(**kwargs)
        current_app.logger.debug("Validation errors: {}".format(errors))

        if errors is not None and len(errors) > 0:
            current_app.logger.warning("Validation errors found")
            self._make_response(400, errors, abort=True)

    def load_request_data(self):
        if request.method in ['GET', 'DELETE']:
            return
        current_app.logger.info("Saving json payload in memory")
        # For now we assume JSON. Later in life we can make this more
        # payload agnostic
        try:
            d = request.data.decode('utf-8')
            g._rq_data = {} if d.strip() == "" else json.loads(d)
        except ValueError:
            return self._make_response(400, "Malformed JSON in request body",
                                       abort=True)

        if self.enforce_json_root and g._rq_data != {} and \
                list(g._rq_data.keys()) != [self._payload_root()]:
            msg = "Invalid JSON root in request body"
            current_app.logger.error(msg)
            current_app.logger.debug(
                "Found {}, expecting {}".format(
                    list(g._rq_data.keys()), self._payload_root()))
            return self._make_response(400, msg, abort=True)
        elif self._payload_root() in list(g._rq_data.keys()):
                current_app.logger.debug("Removing JSON root from rq payload")
                g._rq_data = g._rq_data[self._payload_root()]
        current_app.logger.debug("g._rq_data: {}".format(g._rq_data))
        return g._rq_data

    @wraps(f)
    def decorator(self, *args, **kwargs):
        current_app.logger.info("Got {} request".format(request.method))
        current_app.logger.info("Endpoint: {}".format(request.url))
        if request.method not in self.allowed_methods:
            msg = "Request method {} is unavailable".format(request.method)
            current_app.logger.error(msg)
            return self._make_response(405, msg, abort=True)

        current_app.logger.info("Checking db table/collection is defined")
        if self.enforce_payload_collection and self.db_collection is None:
            msg = "No DB collection defined"
            current_app.logger.error(msg)
            return make_response(Response(msg, 424))

        if request.method in ['POST', 'PUT', 'PATCH']:
            load_request_data(self)

        check_authentication(self, **kwargs)
        if kwargs.get('obj_id', False):
            kwargs['obj_id'] = self.fiddle_id(kwargs['obj_id'])
            self._get_instance(**kwargs)
        else:
            g._resource_instance = {}

        if request.method in ['POST', 'PUT', 'PATCH']:
            check_authorization(self)
            r = self.transform_record(g._rq_data.get(self._payload_root(),
                                                     g._rq_data))
            g._saveable_record = dict(self.merge_record_data(
                r, dict(getattr(g, '_resource_instance', r))))
            validate_request(self, data=g._saveable_record)
        else:
            check_authorization(self)
            validate_request(self)
        return f(self, *args, **kwargs)
    return decorator
116490
function onAuthorizedAccess() {
          if (angular.isFunction(permission.onAuthorized)) {
            permission.onAuthorized()($element);
          } else {
            var onAuthorizedMethodName = $permission.defaultOnAuthorizedMethod;
            PermPermissionStrategies[onAuthorizedMethodName]($element);
          }
        }
221836
async def check_permission(request, permission, context=None):
    

    await check_authorized(request)
    allowed = await permits(request, permission, context)
    if not allowed:
        raise web.HTTPForbidden()
287758
def _make_request(self, method, url, post_data=None, body=None):
        
        if not self.connection:
            self._connect()
        try:
            self.connection.close()
        except:
            pass
        self.connection.connect()
        headers = {}
        if self.auth_header:
            headers["Authorization"] = self.auth_header
        self.connection.request(method, url, body, headers)
        resp = self.connection.getresponse()
        return resp
361112
def __sethead(self, access_token):
        """"""
        self.access_token = access_token
        now = calendar.timegm(datetime.datetime.now().timetuple())
        self.expiration = now + 1800
        self.head = {"Authorization": "Bearer %s" % access_token,
                     "User-Agent": self.user_agent
                     }
934162
function (done) {
      user.authorizedScope(function (err, scopes) {
        if (err) { return done(err) }
        done(null, scopes)
      })
    }
1022527
def on_authenticated(self, authorization):
        

        # Acquire condition
        self.is_authenticating.acquire()

        # Store authorization for future calls
        self.authorization = authorization

        print('Authentication successful - authorization: %r' % self.authorization)

        # Authentication complete
        self.is_authenticating.notify_all()
        self.is_authenticating.release()
705710
def is_authorized(hijack, hijacked):
    '''
    
    '''
    authorization_check = import_string(hijack_settings.HIJACK_AUTHORIZATION_CHECK)
    return authorization_check(hijack, hijacked)