コード例 #1
0
ファイル: views.py プロジェクト: fiatjaf/formspree
def google_call(hashid):
    form = Form.get_with(hashid=hashid)
    session["ggl:form"] = form.hashid

    hint = form.email
    if not form.email.endswith("@gmail.com") and current_user.email.endswith(
        "@gmail.com"
    ):
        hint = current_user.email

    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        settings.GOOGLE_CLIENT_CONFIG,
        scopes=["https://www.googleapis.com/auth/drive.file"],
    )
    flow.redirect_uri = url_for(
        "google_callback",
        _external=True,
        _scheme="https",  # can't figure out how to get this to honor PREFERRED_URL_SCHEME
    )
    authorization_url, _ = flow.authorization_url(
        access_type="offline",
        login_hint=hint,
        prompt="consent",
        state=hashid,
        include_granted_scopes="true",
    )
    return redirect(authorization_url)
コード例 #2
0
ファイル: google_auth.py プロジェクト: harussani/thewolf
def auth():
    app.logger.debug(request.url_root)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES)
    flow.redirect_uri = url_for('oauth2callback', _external=True)
    authorization_url, state = flow.authorization_url(
            access_type='offline',
            login_hint=app.config['GOOGLE_USER_HINT'],
            include_granted_scopes='true')
    session['state'] = state
    return redirect(authorization_url)
コード例 #3
0
def authorize():
    flow = get_flow()
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    authorization_url, state = flow.authorization_url(
        access_type='offline',
        include_granted_scopes='true')

    # Store the state so the callback can verify the auth server response.
    flask.session['state'] = state

    return flask.redirect(authorization_url)
コード例 #4
0
ファイル: server.py プロジェクト: mearajennifer/jobtracker
def authorize():
    # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                                                   scopes=SCOPES)

    flow.redirect_uri = 'http://yourjobtracker.com/oauth2callback'

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    # Store the state so the callback can verify the auth server response.
    session['state'] = state

    return redirect(authorization_url)
コード例 #5
0
ファイル: quickstart_web.py プロジェクト: AITW/api-samples
def authorize():
  # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow
  # steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
  authorization_url, state = flow.authorization_url(
      # This parameter enables offline access which gives your application
      # both an access and refresh token.
      access_type='offline',
      # This parameter enables incremental auth.
      include_granted_scopes='true')

  # Store the state in the session so that the callback can verify that
  # the authorization server response.
  flask.session['state'] = state

  return flask.redirect(authorization_url)
コード例 #6
0
ファイル: google_auth.py プロジェクト: nexocodecom/nisse.io
def google_authorize(store: OAuthStore):
    # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
    flow = get_flow()
    # The URI created here must exactly match one of the authorized redirect URIs
    # for the OAuth 2.0 client, which you configured in the API Console. If this
    # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
    # error.
    flow.redirect_uri = flask.url_for('nisseoauthcallback',
                                      _external=True,
                                      _scheme=get_request_scheme())
    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        prompt='consent',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')
    # Store the state so the callback can verify the auth server response.
    store.set_state(state)
    return flask.redirect(authorization_url)
コード例 #7
0
ファイル: views.py プロジェクト: adebruine/personal-site
    def get(self, request, *args, **kwargs):
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
            gsheets_settings.CLIENT_SECRETS, scopes=gsheets_settings.SCOPES)

        # The URI created here must exactly match one of the authorized redirect URIs
        # for the OAuth 2.0 client, which you configured in the API Console. If this
        # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
        # error.
        flow.redirect_uri = get_oauth_cb_url(
            request, cb_hostname=gsheets_settings.OAUTH_REDIRECT_HOSTNAME)
        logger.debug(f'flow redirect URI is {flow.redirect_uri}')

        authorization_url, state = flow.authorization_url(
            # Enable offline access so that you can refresh an access token without
            # re-prompting the user for permission. Recommended for web server apps.
            access_type='offline',
            prompt='consent',
            # Enable incremental authorization. Recommended as a best practice.
            include_granted_scopes='true')

        # Store the state so the callback can verify the auth server response.
        request.session['state'] = state

        return redirect(authorization_url)
コード例 #8
0
def setup():
    raw_input("""
Google Drive C2 Setup
---------------------

You'll need a Google Account to continue. You may
want to create a new Google Account for c2.

Create a New Project here:

https://console.developers.google.com/apis

[continue]""")
    raw_input("""
Create Credentials for your project.

Select OAuth Client ID Credentials of type "Other".

Click "Download JSON" and place the .json file in this directory.

It must be named "client_secrets.json"

[continue]""")
    # verbose("Creating flow object from client_secrets.json...")

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        'client_secrets.json',
        scopes=[
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/spreadsheets'
        ])
    flow.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'

    auth_uri, state = flow.authorization_url(access_type='offline')

    debug("state: %s" % state)
    print "\nOpen this URL in your browser: \n\n" + auth_uri + "\n"
    auth_code = raw_input('Enter the authentication code: ')
    # verbose("Retrieving full credentials...")
    flow.fetch_token(code=auth_code)
    credentials = flow.credentials
    raw_input("""
Success! API Credentials Created!

Copy and Paste this code in the top of this script to save this credential

credentials.append(google.oauth2.credentials.Credentials(
    "",
    refresh_token="%s",
    client_id="%s",
    client_secret="%s",
    token_uri="https://accounts.google.com/o/oauth2/token"))

When you run this script, you can specify which credentials to use via -c

[continue]
""" % (credentials.refresh_token, credentials.client_id,
        credentials.client_secret))
    raw_input("""
Enable the Google Drive API:
https://console.developers.google.com/apis/api/drive.googleapis.com/overview

[continue]
""")
    raw_input("""
IMPORTANT PERFORMANCE TIP:

1. Create a second Drive API project
2. Run --setup again
3. Use one credential for each running script, avoiding rate limits

[continue]
""")
    print "\nSetup success!"
    exit()
コード例 #9
0
import google.oauth2.credentials
import google_auth_oauthlib.flow

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secert.json',
    scopes=['https://www.googleapis.com/auth/yt-analytics.readonly'])
flow.redirect_uri = "http://127.0.0.1:5000/hello"
authorization_url, state = flow.authorization_url(
    # Enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type='offline',
    # Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes='true')
コード例 #10
0
def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    # How to create cred https://stackoverflow.com/a/52222827/2138792
    client_secrets_file = get_client_secrets_file()
    destination_play_list = get_dest_playlist()
    source_play_list = 'LM'  # Replace if not using liked music
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes,redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    # credentials = flow.run_local_server()
    auth_url, _ = flow.authorization_url(prompt='consent')
    print(auth_url)
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)
    credentials=flow.credentials
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    def getplaylistvids(pid):
        request = youtube.playlistItems().list(
            part='contentDetails',
            playlistId="LM"
        )
        response = request.execute()
        if 'pageInfo' in response:
            pageInfo = response['pageInfo']
            if 'totalResults' in pageInfo:
                maxResults = pageInfo['totalResults']

        request = youtube.playlistItems().list(
            part='contentDetails',
            playlistId=pid,
            maxResults=50 if maxResults > 50 else maxResults
        )
        response = request.execute()
        print(response)
        vids = []

        if 'items' in response:
            items = response['items']
            for item in items:
                if "contentDetails" in item:
                    vids.append(item['contentDetails']['videoId'])
        while len(vids) < maxResults:
            sleep(1)
            if 'nextPageToken' in response:
                request = youtube.playlistItems().list(
                    part='contentDetails',
                    playlistId=pid,
                    maxResults=50,
                    pageToken= response['nextPageToken'],
                )
            else:
                request = youtube.playlistItems().list(
                    part='contentDetails',
                    playlistId=pid,
                    maxResults=50,
                )
            response = request.execute()
            print(response)

            if 'items' in response:
                items = response['items']
                for item in items:
                    if "contentDetails" in item:
                        vids.append(item['contentDetails']['videoId'])
            if 'nextPageToken' in response:
                nextPageToken = response['nextPageToken']
            else:
                break
        return vids

    source_vids = getplaylistvids(source_play_list)
    destination_vids = getplaylistvids(destination_play_list)
    vids = set(source_vids) - set(destination_vids)
    print(vids)
    for vid in vids:
        try:
            request = youtube.playlistItems().insert(
                part="snippet",
                body={
                    "snippet": {
                        "playlistId": destination_play_list,
                        "resourceId": {
                            "videoId": vid,
                            "kind": "youtube#video"
                        }
                    }
                }
            )
            response = request.execute()
            print(response)
            sleep(1)
        except Exception as e:
            print(e)
コード例 #11
0
ファイル: google_api.py プロジェクト: mizabrik/diht-schedule
 def get_authentication_url(callback_uri):
     flow = google_auth_oauthlib.flow.Flow.from_client_config(
         CLIENT_CONFIG, scopes=SCOPES, redirect_uri=callback_uri)
     return flow.authorization_url(access_type='offline')
コード例 #12
0
    def calendar(field):

        # https://www.googleapis.com/auth/calendar.readonly

        # Successfully installed cachetools-4.1.0 google-auth-1.14.0 google-auth-httplib2-0.0.3 google-auth-oauthlib-0.4.1 httplib2-0.17.2 oauthlib-3.1.0 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.0

        # 4/ywEX3hVZgLcTCxzQf9qAMRS_GJTLEhMtDfhTpeNCACYZWAVl31ecVho

        ready = False

        subfields = [{
            "name":
            "credentials",
            "description":
            "\n".join([
                "Go to the Link below.", "Create a new project.",
                "Enable Calendar API.", "Create credentials (OAuth, Other).",
                "Download the JSON and paste it above."
            ]),
            "link": {
                "name": "Google API's",
                "url": "https://console.developers.google.com/apis/"
            }
        }]

        credentials = json.loads(
            field.value['credentials']
        ) if field.value and field.value.get("credentials") else {}

        if credentials and "token" not in credentials:

            if not field.value.get("code"):

                flow = google_auth_oauthlib.flow.Flow.from_client_config(
                    credentials,
                    scopes=[
                        'https://www.googleapis.com/auth/calendar.readonly'
                    ],
                    redirect_uri='urn:ietf:wg:oauth:2.0:oob')

                url, state = flow.authorization_url(
                    prompt='consent',
                    access_type='offline',
                    include_granted_scopes='true')

                credentials["state"] = state

                subfields.append({
                    "name":
                    "code",
                    "description":
                    "\n".join([
                        "Go to the Link below.", "Click Advanced.",
                        "Authorise access to your Calendars.",
                        "Copy the Code and paste it above."
                    ]),
                    "link": {
                        "name": "Authorize Calendar Access",
                        "url": url
                    }
                })

            else:

                flow = google_auth_oauthlib.flow.Flow.from_client_config(
                    credentials,
                    scopes=[
                        'https://www.googleapis.com/auth/calendar.readonly'
                    ],
                    redirect_uri='urn:ietf:wg:oauth:2.0:oob',
                    state=credentials['state'])

                flow.fetch_token(code=field.value["code"])

                credentials = json.loads(flow.credentials.to_json())

        if credentials and "token" in credentials:

            service = googleapiclient.discovery.build(
                'calendar',
                'v3',
                credentials=google.oauth2.credentials.Credentials(
                    **credentials))

            options = []
            labels = {}
            page_token = None

            while True:

                calendar_list = service.calendarList().list(
                    pageToken=page_token).execute()

                for calendar in calendar_list['items']:
                    options.append(calendar['id'])
                    labels[calendar['id']] = calendar["summary"]

                page_token = calendar_list.get('nextPageToken')

                if not page_token:
                    break

            subfields.append({
                "name": "watch",
                "description": "The Calendar you'd like to watch.",
                "options": options,
                "labels": labels
            })

            ready = True

        field.fields = opengui.Fields(field.value, field.original, subfields)

        if credentials:
            field.fields["credentials"].value = json.dumps(credentials)

        return ready
コード例 #13
0
    {
      "installed": {
        "client_id": "YOUR_CLIENT_ID_HERE",
        "client_secret": "YOUR_CLIENT_SECRET_HERE",
        "redirect_uris": ["http://*****:*****@app.route('/')
    def root():
        return flask.redirect(authorization_url)

    @app.route('/redirect')
    def redirect():
        flow.fetch_token(authorization_response=flask.request.url)
        result = {
            'access_token': flow.credentials.token,
            'refresh_token': flow.credentials.refresh_token,
        }
        return result
コード例 #14
0
ファイル: main.py プロジェクト: COSCUP/COSCUP-Volunteer
def oauth2callback():
    ''' oauth2callback '''
    if 'r' in request.args and request.args['r'].startswith('/'):
        session['r'] = request.args['r']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        './client_secret.json',
        scopes=(
            'openid',
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/userinfo.profile',
        ),
        redirect_uri=f'https://{setting.DOMAIN}/oauth2callback',
    )

    if 'code' not in request.args:
        authorization_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true',
            state=hashlib.sha256(os.urandom(2048)).hexdigest(),
        )

        session['state'] = state
        return redirect(authorization_url)

    url = request.url.replace('http://', 'https://')
    url_query = parse_qs(urlparse(url).query)

    if 'state' in url_query and url_query['state'] and \
            url_query['state'][0] == session.get('state'):
        flow.fetch_token(authorization_response=url)

        auth_client = discovery.build('oauth2',
                                      'v2',
                                      credentials=flow.credentials,
                                      cache_discovery=False)
        user_info = auth_client.userinfo().get().execute()

        # ----- save oauth info ----- #
        OAuth.add(mail=user_info['email'],
                  data=user_info,
                  token=flow.credentials)

        # ----- Check account or create ----- #
        owner = OAuth.owner(mail=user_info['email'])
        if owner:
            user = User(uid=owner).get()
        else:
            user = User.create(mail=user_info['email'])
            MailLetterDB().create(uid=user['_id'])

        user_session = USession.make_new(uid=user['_id'],
                                         header=dict(request.headers))
        session['sid'] = user_session.inserted_id

        if 'r' in session:
            redirect_path = session['r']
            logging.info('login r: %s', redirect_path)
            session.pop('r', None)
            session.pop('state', None)
            return redirect(redirect_path)

        return redirect(url_for('index', _scheme='https', _external=True))

    session.pop('state', None)
    return redirect(url_for('oauth2callback', _scheme='https', _external=True))
コード例 #15
0
def start_google_flow() -> str:
    '''Start Google flow and generate authorization url.'''
    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        client_config, scopes=scopes, redirect_uri=redirect_uri)

    return flow.authorization_url()
コード例 #16
0
def auth():
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('credentials.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])
    flow.redirect_uri = url_for('callback', _external=True, _scheme="https")
    authorization_url, state = flow.authorization_url(access_type="offline", include_granted_scopes="true")
    session["state"] = state
    return redirect(authorization_url)
コード例 #17
0
from google.auth.transport import requests

api = Blueprint('google', __name__)
auth_engine = AuthEngine()

# setup a flow object to manage OAuth exchange.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    GOOGLE_SECRETS,
    scopes=[
        'https://www.googleapis.com/auth/plus.login',
        'https://www.googleapis.com/auth/plus.me',
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile',
    ])
flow.redirect_uri = 'http://*****:*****@api.route('/', methods=['GET'])
def google_login() -> redirect or tuple:
    """
    Google OAuth login resource for initiating OAuth Protocol.
    Returns:
        redirect to google login page if no auth token provided, otherwise,
        api will return api access and refresh tokens if google token is valid
        along with 200 status code, or 400 status code with error message if
        google token.
    """
コード例 #18
0
def auth_begin(request):
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        client_json_path, scopes=['email'])
    flow.redirect_uri = 'http://cursdb.com:8000/redirect'
    authorization_url, state = flow.authorization_url(access_type='offline', )
    return redirect(authorization_url)