Setup an HTTP session authorized by OAuth2.
357294
def _setupHttp(self):
        
        if self._http == None:
            http = httplib2.Http()
            self._http = self._credentials.authorize(http)
62512
def get(self, url):
        
        logger.debug('Making GET request to %s', url)
        return self.oauth_session.get(url)
1114522
async def login(self, client_name, request, redirect_uri=None, **params):
        
        client = self.client(client_name, logger=self.app.logger)

        redirect_uri = redirect_uri or self.cfg.redirect_uri or '%s://%s%s' % (
            request.scheme, request.host, request.path)
        session = await self.app.ps.session(request)

        if isinstance(client, OAuth1Client):
            oauth_verifier = request.query.get('oauth_verifier')
            if not oauth_verifier:

                # Get request credentials
                token, secret = await client.get_request_token(
                    oauth_callback=redirect_uri)

                # Save the credentials in current user session
                session['oauth_token'] = token
                session['oauth_token_secret'] = secret

                url = client.get_authorize_url()
                raise muffin.HTTPFound(url)

            # Check request_token
            oauth_token = request.query.get('oauth_token')
            if session['oauth_token'] != oauth_token:
                raise muffin.HTTPForbidden(reason='Invalid token.')

            client.oauth_token = oauth_token
            client.oauth_token_secret = session.get('oauth_token_secret')

            # Get access tokens
            return client, await client.get_access_token(oauth_verifier)

        if isinstance(client, OAuth2Client):
            code = request.query.get('code')
            if not code:

                # Authorize an user
                state = sha1(str(random()).encode('ascii')).hexdigest()
                session['oauth_secret'] = state
                url = client.get_authorize_url(
                    redirect_uri=redirect_uri, state=state, **params)
                raise muffin.HTTPFound(url)

            # Check state
            state = request.query.get('state')
            oauth_secret = session.pop('oauth_secret', '')
            if oauth_secret != state:
                raise muffin.HTTPForbidden(reason='Invalid token "%s".' % oauth_secret)

            # Get access token
            return client, await client.get_access_token(code, redirect_uri=redirect_uri)

        return client
987618
def authenticate_redirect(self, callback_uri=None, cancel_uri=None,
                              extended_permissions=None, callback=None):
        
        self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME)

        scope = self._BASE_SCOPE
        if extended_permissions:
            scope += extended_permissions

        args = {'client_id': self.settings[self._CLIENT_ID_SETTING],
                'redirect_uri': self.oauth2_redirect_uri(callback_uri),
                'scope': ','.join(scope)}

        # If cookie_secret is set, use it for GitHub's state value
        if not self.state and 'cookie_secret' in self.settings:
            sha1 = hashlib.sha1(self.settings['cookie_secret'])
            self.state = str(sha1.hexdigest())

        # If state is set, add it to args
        if self.state:
            args['state'] = self.state

        LOGGER.info('Redirect args: %r', args)

        # Redirect the user to the proper URL
        self.redirect(self._OAUTH_AUTHORIZE_URL +
                      auth.urllib_parse.urlencode(args))
        callback()
394183
def connect(provider_id):
    """"""
    provider = get_provider_or_404(provider_id)
    callback_url = get_authorize_callback('connect', provider_id)
    allow_view = get_url(config_value('CONNECT_ALLOW_VIEW'))
    pc = request.form.get('next', allow_view)
    session[config_value('POST_OAUTH_CONNECT_SESSION_KEY')] = pc
    return provider.authorize(callback_url)
479381
def requests_session(self, *args, **kwargs):
        
        import requests
        auth1 = self.generate_auth()
        return requests.Session(*args, auth=auth1, **kwargs)
939359
def _make_session():
        

        sess = requests.Session()
        sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False))
        sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False))

        return sess
587736
def authorized(remote_app=None):
    """"""
    if remote_app not in current_oauthclient.handlers:
        return abort(404)

    state_token = request.args.get('state')

    # Verify state parameter
    try:
        assert state_token
        # Checks authenticity and integrity of state and decodes the value.
        state = serializer.loads(state_token)
        # Verify that state is for this session, app and that next parameter
        # have not been modified.
        assert state['sid'] == _create_identifier()
        assert state['app'] == remote_app
        # Store next URL
        set_session_next_url(remote_app, state['next'])
    except (AssertionError, BadData):
        if current_app.config.get('OAUTHCLIENT_STATE_ENABLED', True) or (
           not(current_app.debug or current_app.testing)):
            abort(403)

    try:
        handler = current_oauthclient.handlers[remote_app]()
    except OAuthException as e:
        if e.type == 'invalid_response':
            abort(500)
        else:
            raise

    return handler
946765
def setup_oauth_client(self, url=None):
        
        if url and "://" in url:
            server, endpoint = self._deconstruct_url(url)
        else:
            server = self.client.server

        if server not in self._server_cache:
            self._add_client(server)

        if server == self.client.server:
            self.oauth = OAuth1(
                client_key=self.store["client-key"],
                client_secret=self.store["client-secret"],
                resource_owner_key=self.store["oauth-access-token"],
                resource_owner_secret=self.store["oauth-access-secret"],
            )
            return self.oauth
        else:
            return OAuth1(
                client_key=self._server_cache[server].key,
                client_secret=self._server_cache[server].secret,
            )
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle
899265
def _post(self, url, **kw):
        '''
        
        '''
        headers = kw.pop('headers', {})
        headers.setdefault('Authorization', self.AUTHORIZATION_HEADER)
        kw['headers'] = headers
        resp = self.session.post(url, **kw)
        self._raise_for_status(resp)
        return resp
147177
def authorized_http(client_id, client_secret, apps, file=None):
    
    if not os.path.exists(CREDENTIAL_DIR):
        os.makedirs(CREDENTIAL_DIR)

    credential_path = file or CREDENTIAL_PATH
    storage = Storage(credential_path)
    credentials = storage.get()

    scopes = set([
        "https://www.googleapis.com/auth/{0}.readonly".format(app)
        for app in apps
        ])

    if (not credentials or credentials.invalid
            or not scopes <= credentials.scopes):
        flow = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope=scopes,
            redirect_uri=REDIRECT_URI)
        flow.user_agent = USER_AGENT

        # Do not parse did command-line options by OAuth client
        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, storage, flags)

    return credentials.authorize(httplib2.Http())
1243386
def _authenticate(self):
        """"""
        if not self._get_provider_option(
                'auth_username') or not self._get_provider_option('auth_password'):
            raise Exception(
                'No valid authentication data passed, expected: auth-username and auth-password')
        response = self._request_login(self._get_provider_option('auth_username'),
                                       self._get_provider_option('auth_password'))
        if 'ssid' in response:
            self.ssid = response['ssid']
            domains = self.domains_list()
            if any((domain['name'] == self.domain for domain in domains)):
                self.domain_id = self.domain
            else:
                raise Exception("Unknown domain {}".format(self.domain))
        else:
            raise Exception("No SSID provided by server")
648995
def create_authserver(self, domainid, data):
        """"""
        return self.api_call(
            ENDPOINTS['authservers']['new'],
            dict(domainid=domainid),
            body=data)
1256230
def _authenticate_user(self, user, password):
        
        headers = self._get_headers()
        params = {
                'username': user,
                'password': password,
                'grant_type': 'password',
                }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate %s" % (user))
            response.raise_for_status()
156999
def set_oauth_session(self, provider, oauth_response):
        
        # Get this provider key names for token_key and token_secret
        token_key = self.appbuilder.sm.get_oauth_token_key_name(provider)
        token_secret = self.appbuilder.sm.get_oauth_token_secret_name(provider)
        # Save users token on encrypted session cookie
        session["oauth"] = (
            oauth_response[token_key],
            oauth_response.get(token_secret, ""),
        )
        session["oauth_provider"] = provider
356003
def _authenticate(self):
        """"""
        login_info = self._apicall('login')
        self.api_session_id = login_info['apisessionid']
        if not self.api_session_id:
            raise Exception('Login failed')
        # query ttl and verify access to self.domain:
        zone_info = self._apicall('infoDnsZone', domainname=self.domain)
        self.zone_ttl = zone_info['ttl']