Validates an OAuth request using the python-oauth2 library:
            https://github.com/simplegeo/python-oauth2
761731
def is_valid_request(self, request, parameters={},
                         fake_method=None, handle_error=True):
        '''
        

        '''
        try:
            # Set the parameters to be what we were passed earlier
            # if we didn't get any passed to us now
            if not parameters and hasattr(self, 'params'):
                parameters = self.params

            method, url, headers, parameters = self.parse_request(
                request, parameters, fake_method)

            oauth_request = oauth2.Request.from_request(
                method,
                url,
                headers=headers,
                parameters=parameters)

            self.oauth_server.verify_request(
                oauth_request, self.oauth_consumer, {})

        except oauth2.MissingSignature, e:
            if handle_error:
                return False
            else:
                raise e
        # Signature was valid
        return True
311470
def check(*args)
      raise_authentication_error unless authenticated?
      params = arguments(args, required: [:client_id, :access_token]).params

      if arguments.client_id
        begin
          get_request("/applications/#{arguments.client_id}/tokens/#{arguments.access_token}", params)
        rescue Github::Error::NotFound
          nil
        end
      else
        raise raise_app_authentication_error
      end
    end
104253
def parse_authentication_request(self, request_body, http_headers=None):
        # type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest
        

        auth_req = AuthorizationRequest().deserialize(request_body)

        for validator in self.authentication_request_validators:
            validator(auth_req)

        logger.debug('parsed authentication_request: %s', auth_req)
        return auth_req
1145007
def validate_repo_url(url):
    
    try:
        if "github.com" in url:
            return re.findall(r"https?://w?w?w?.?github.com/[\w\-]+/[\w.-]+", url)[0]
        elif "bitbucket.org" in url:
            return re.findall(r"https?://bitbucket.org/[\w.-]+/[\w.-]+", url)[0] + "/src/"
        elif "launchpad.net" in url:
            return re.findall(r"https?://launchpad.net/[\w.-]+", url)[0]
        elif "sourceforge.net" in url:
            mo = re.match(r"https?://sourceforge.net/projects/"
                          r"([\w.-]+)/", url, re.I)
            template = "https://sourceforge.net/p/{}/code/HEAD/tree/trunk/src/"
            return template.format(mo.groups()[0])
    except (IndexError, AttributeError):
        pass
    return ""
281165
def make_request(self, url, params, auth=None):
        
        req = urllib2.Request(url + urllib.urlencode(params))

        if auth:
            req.add_header('AUTHORIZATION', 'Basic ' + auth)

        return urllib2.urlopen(req)
1106727
def _validate_auth_scheme(self, req):
        

        if not req.auth:
            raise AuthRequired(**{
                'detail': 'You must first login to access the requested '
                          'resource(s). Please retry your request using '
                          'OAuth 2.0 Bearer Token Authentication as '
                          'documented in RFC 6750. If you do not have an '
                          'access_token then request one at the token '
                          'endpdoint of: %s' % self.token_endpoint,
                'headers': self._error_headers,
                'links': 'tools.ietf.org/html/rfc6750#section-2.1',
            })
        elif req.auth_scheme != 'bearer':
            raise AuthRequired(**{
                'detail': 'Your Authorization header is using an unsupported '
                          'authentication scheme. Please modify your scheme '
                          'to be a string of: "Bearer".',
                'headers': self._error_headers,
                'links': 'tools.ietf.org/html/rfc6750#section-2.1',
            })
597518
def verify_request_common(consumers, url, method, headers, params):
    
    log.debug("consumers %s", consumers)
    log.debug("url %s", url)
    log.debug("method %s", method)
    log.debug("headers %s", headers)
    log.debug("params %s", params)

    oauth_server = LTIOAuthServer(consumers)
    oauth_server.add_signature_method(
        SignatureMethod_PLAINTEXT_Unicode())
    oauth_server.add_signature_method(
        SignatureMethod_HMAC_SHA1_Unicode())

    # Check header for SSL before selecting the url
    if headers.get('X-Forwarded-Proto', 'http') == 'https':
        url = url.replace('http:', 'https:', 1)

    oauth_request = Request_Fix_Duplicate.from_request(
        method,
        url,
        headers=dict(headers),
        parameters=params
    )
    if not oauth_request:
        log.info('Received non oauth request on oauth protected page')
        raise LTIException('This page requires a valid oauth session '
                           'or request')
    try:
        # pylint: disable=protected-access
        oauth_consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_server.lookup_consumer(oauth_consumer_key)
        if not consumer:
            raise oauth2.Error('Invalid consumer.')
        oauth_server.verify_request(oauth_request, consumer, None)
    except oauth2.Error:
        # Rethrow our own for nice error handling (don't print
        # error message as it will contain the key
        raise LTIException("OAuth error: Please check your key and secret")

    return True
939172
def oauth2_auth_url_cli(redirect_uri=None, client_id=None,
                        base_url=OH_BASE_URL):
    
    result = oauth2_auth_url(redirect_uri, client_id, base_url)
    print('The requested URL is : \r')
    print(result)
735452
function OAuth2Error(message, code, uri, status) {
  Error.call(this);
  this.message = message;
  this.code = code || 'server_error';
  this.uri = uri;
  this.status = status || 500;
}
1180773
def _get_request_token(self):
        
        
        params = {
            'oauth_callback': self.get_callback_url()
        }
        
        
        response, content = self.client().request(self.request_token_url,
            "POST", body=urllib.urlencode(params))
        
        content = smart_unicode(content)

        if not response['status'] == '200':
            raise OAuthError(_(
                u"Invalid status code %s while obtaining request token from %s: %s") % (
                    response['status'], self.request_token_url, content))
        
        token = dict(urlparse.parse_qsl(content))
        
        return oauth.Token(token['oauth_token'], token['oauth_token_secret'])
1228593
def _validate_request(endpoint, file_type='json', data=None, params=None):
        
        if not isinstance(endpoint, string_types) or endpoint.strip() == '':
            raise ClientException("Must submit `endpoint` for DHIS2 API")
        if not isinstance(file_type, string_types) or file_type.lower() not in ('json', 'csv', 'xml', 'pdf', 'xlsx'):
            raise ClientException("Invalid file_type: {}".format(file_type))
        if params:
            if not isinstance(params, (dict, list)):
                raise ClientException("`params` must be a dict or list of tuples, not {}".format(params.__class__.__name__))
            if isinstance(params, list) and not all([isinstance(elem, tuple) for elem in params]):
                raise ClientException("`params` list must all be tuples")
        if data and not isinstance(data, dict):
            raise ClientException("`data` must be a dict, not {}".format(data.__class__.__name__))
76076
def oauth2callback(self, view_func):
        

        @wraps(view_func)
        def decorated(*args, **kwargs):
            params = {}

            # Check sig
            if 'state' in request.args:
                params.update(**self.parse_state(request.args.get('state')))
                if params.pop('sig', None) != make_secure_token(**params):
                    return self.login_manager.unauthorized()

            code = request.args.get('code')

            # Web server flow
            if code:
                token = self.exchange_code(
                    code,
                    url_for(
                        request.endpoint,
                        _external=True,
                        _scheme=self.redirect_scheme,
                    ),
                )
                userinfo = self.get_userinfo(token['access_token'])
                params.update(token=token, userinfo=userinfo)

            # Browser flow
            else:
                if params:
                    params.update(dict(request.args.items()))
                else:
                    return '''
                    <script>
                      window.onload = function() {
                        location.href = '?' + window.location.hash.substr(1);
                      };
                    </script>
                    '''

            return view_func(**params)

        return decorated
905762
def validate_query_params(self, request):
        
        # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for
        # the ValidationError. This requires extending DRF/DJA Exceptions.
        for qp in request.query_params.keys():
            if not self.query_regex.match(qp):
                raise ValidationError('invalid query parameter: {}'.format(qp))
            if len(request.query_params.getlist(qp)) > 1:
                raise ValidationError(
                    'repeated query parameter not allowed: {}'.format(qp))
959263
def authenticate!
      response = connection.post '/services/oauth2/token' do |req|
        req.body = encode_www_form(params)
      end

      if response.status >= 500
        raise Restforce::ServerError, error_message(response)
      elsif response.status != 200
        raise Restforce::AuthenticationError, error_message(response)
      end

      @options[:instance_url] = response.body['instance_url']
      @options[:oauth_token]  = response.body['access_token']

      @options[:authentication_callback]&.call(response.body)

      response.body
    end
873163
def check_key(request):
    
    try:
        access_key = request.session.get('oauth_token', None)
        if not access_key:
            return False
    except KeyError:
        return False
    return True
1375060
def read_validate_params(self, request):
        
        self.refresh_token = request.post_param("refresh_token")

        if self.refresh_token is None:
            raise OAuthInvalidError(
                error="invalid_request",
                explanation="Missing refresh_token in request body")

        self.client = self.client_authenticator.by_identifier_secret(request)

        try:
            access_token = self.access_token_store.fetch_by_refresh_token(
                self.refresh_token
            )
        except AccessTokenNotFound:
            raise OAuthInvalidError(error="invalid_request",
                                    explanation="Invalid refresh token")

        refresh_token_expires_at = access_token.refresh_expires_at
        self.refresh_grant_type = access_token.grant_type

        if refresh_token_expires_at != 0 and \
                        refresh_token_expires_at < int(time.time()):
            raise OAuthInvalidError(error="invalid_request",
                                    explanation="Invalid refresh token")

        self.data = access_token.data
        self.user_id = access_token.user_id

        self.scope_handler.parse(request, "body")
        self.scope_handler.compare(access_token.scopes)

        return True
447868
def auth(self, request):
        
        try:
            auth = self.gh.authorize(self.username,
                                     self.password,
                                     self.scope,
                                     '',
                                     '',
                                     self.consumer_key,
                                     self.consumer_secret)
            request.session['oauth_token'] = auth.token
            request.session['oauth_id'] = auth.id
        except AuthenticationFailed as e:
            messages.add_message(request, messages.ERROR, message="GITHUB RENEW FAILED : Reason {}".format(e))
            return reverse('user_services')

        return self.callback_url(request)