Ejemplo n.º 1
0
def get_gcal_service(credentials):
    """
    Returns an authorized service for the Google Calendar API
    :param credentials: Credentials stored in the flask session
    :return: Authorized service for the Google Calendar API
    """

    credentials = google.oauth2.credentials.Credentials(
        **credentials
    )

    if credentials.expired:
        print("Cred expired")


    http = urllib3.PoolManager()
    request = google.auth.transport.urllib3.Request(http)
    # credentials.refresh(request)
    # request = requests.Request()
    # credentials.refresh(request)
    service = discovery.build(
        'calendar', 'v3',
        credentials=credentials, cache_discovery=False
    )
    return service
Ejemplo n.º 2
0
async def process(formdata, _session, server: plugins.server.BaseServer):
    js = None
    request = google.auth.transport.urllib3.Request(urllib3.PoolManager())
    # This is a synchronous process, so we offload it to an async runner in order to let the main loop continue.
    id_info = await server.runners.run(
        google.oauth2.id_token.verify_oauth2_token,
        formdata.get("id_token"),
        request,
        server.config.oauth.google_client_id,
    )

    if id_info and "email" in id_info:
        js = {
            "email": id_info["email"],
            "name": id_info["email"],
            "oauth_domain": "www.googleapis.com",
        }
    return js
Ejemplo n.º 3
0
    def __init__(self, options):
        super().__init__()

        self.ssl_context = get_ssl_context(
            options.backend_options.get('ssl-ca-path',
                                        None))  # type: Optional[ssl.Context]
        self.options = options.backend_options  # type: Dict[str, str]
        self.proxy = get_proxy(ssl=True)  # type: str
        self.login = options.backend_login  # type: str
        self.refresh_token = options.backend_password  # type: str

        if self.login == 'adc':
            if g_auth is None:
                raise QuietError(
                    'ADC authentification requires the google.auth module')
            elif self.adc is None:
                import google.auth.transport.urllib3
                import urllib3

                # Deliberately ignore proxy and SSL context when attemping
                # to connect to Compute Engine Metadata server.
                requestor = google.auth.transport.urllib3.Request(
                    urllib3.PoolManager())
                try:
                    credentials, _ = g_auth.default(
                        request=requestor,
                        scopes=[
                            'https://www.googleapis.com/auth/devstorage.full_control'
                        ])
                except g_auth.exceptions.DefaultCredentialsError as exc:
                    raise QuietError(
                        'ADC found no valid credential sources: ' + str(exc))
                type(self).adc = (credentials, requestor)
        elif self.login != 'oauth2':
            raise QuietError(
                "Google Storage backend requires OAuth2 or ADC authentication")

        # Special case for unit testing against local mock server
        hit = re.match(
            r'^gs://!unittest!'
            r'([^/:]+)'  # Hostname
            r':([0-9]+)'  # Port
            r'/([^/]+)'  # Bucketname
            r'(?:/(.*))?$',  # Prefix
            options.storage_url)
        if hit:
            self.hostname = hit.group(1)
            self.port = int(hit.group(2))
            self.bucket_name = hit.group(3)
            self.prefix = hit.group(4) or ''
        else:
            hit = re.match(r'^gs://([^/]+)(?:/(.*))?$', options.storage_url)
            if not hit:
                raise QuietError('Invalid storage URL', exitcode=2)

            self.bucket_name = hit.group(1)
            self.hostname = 'www.googleapis.com'
            self.prefix = hit.group(2) or ''
            self.port = 443

        self.conn = self._get_conn()

        # Check if bucket exists and/or credentials are correct
        path = '/storage/v1/b/' + urllib.parse.quote(self.bucket_name, safe='')
        try:
            resp = self._do_request('GET', path)
        except RequestError as exc:
            if exc.code == 404:
                raise DanglingStorageURLError("Bucket '%s' does not exist" %
                                              self.bucket_name)
            exc = _map_request_error(exc, None)
            if exc:
                raise exc
            raise
        self._parse_json_response(resp)
Ejemplo n.º 4
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os

from google.auth import _helpers
import google.auth.transport.urllib3
import pytest
import urllib3

HERE = os.path.dirname(__file__)
DATA_DIR = os.path.join(HERE, 'data')
HTTP = urllib3.PoolManager()
TOKEN_INFO_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo'


@pytest.fixture
def service_account_file():
    """The full path to a valid service account key file."""
    yield os.path.join(DATA_DIR, 'service_account.json')


@pytest.fixture
def request():
    """A transport.request object."""
    yield google.auth.transport.urllib3.Request(HTTP)

Ejemplo n.º 5
0
import json
import os

from google.auth import _helpers
import google.auth.transport.requests
import google.auth.transport.urllib3
import pytest
import requests
import urllib3

HERE = os.path.dirname(__file__)
DATA_DIR = os.path.join(HERE, "data")
SERVICE_ACCOUNT_FILE = os.path.join(DATA_DIR, "service_account.json")
AUTHORIZED_USER_FILE = os.path.join(DATA_DIR, "authorized_user.json")
URLLIB3_HTTP = urllib3.PoolManager(retries=False)
REQUESTS_SESSION = requests.Session()
REQUESTS_SESSION.verify = False
TOKEN_INFO_URL = "https://www.googleapis.com/oauth2/v3/tokeninfo"


@pytest.fixture
def service_account_file():
    """The full path to a valid service account key file."""
    yield SERVICE_ACCOUNT_FILE


@pytest.fixture
def authorized_user_file():
    """The full path to a valid authorized user file."""
    yield AUTHORIZED_USER_FILE
Ejemplo n.º 6
0
# compliance with the License. You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
import aws_xray_sdk.core
import boto3
import google.auth.transport.urllib3
import google.oauth2.id_token
import os
import urllib3

aws_xray_sdk.core.patch(["boto3"])
http = urllib3.PoolManager()
request = google.auth.transport.urllib3.Request(http)
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])


def handler(event, context):
    # The input includes the "Bearer " prefix, so strip it out.
    encoded_token = event["authorizationToken"][7:]
    try:
        decoded_token = google.oauth2.id_token.verify_token(encoded_token, request, os.environ["CLIENT_ID"])
    except ValueError:
        raise Exception("Unauthorized")

    if decoded_token["iss"] not in ("accounts.google.com", "https://accounts.google.com"):
        print(f"Unexpected token issuer {decoded_token['iss']}, rejecting call")
        raise Exception("Unauthorized")