Beispiel #1
0
def request_oauth2_credentials():
    '''
    Steps:
		1. Set authorization parameters
		2. Redirect to Google's OAuth 2.0 server
		3. Google prompts the user for consent
		4. Handle the OAuth 2.0 server response
		5. Exchange authorization code for refresh and access tokens
	'''

    # Use the client_secret.json file to identify the application requesting
    # authorization. The client ID (from that file) and access scopes are required.
    flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                         scopes=[YOUTUBE_UPLOAD_SCOPE])

    # Indicate where the API server will redirect the user after the user completes
    # the authorization flow. The redirect URI is required. The value 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 in your
    # Google API's account you will get a 'redirect_uri_mismatch' error.
    flow.redirect_uri = REDIRECT_URI

    # Generate URL for request to Google's OAuth 2.0 server.
    # Use kwargs to set optional request parameters.
    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',
    )

    # Your application redirects the user to Google along with the list of requested permissions.
    # The user decides whether to grant the permissions to your application.
    print(authorization_url)
    # To-DO: This step should be handled by a web server automatically and should not require user input when in production
    authorization_response = input(
        "Go to the above url, allow permissions and then when you get redirected to a new page, paste the url here"
    )

    # After the web server receives the authorization code, it can begin the exchange the authorization code for an access token.
    # First verify the authoriation server response by providing the same state token to protect against XSRF
    flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                         scopes=[YOUTUBE_UPLOAD_SCOPE],
                                         state=state)
    flow.redirect_uri = REDIRECT_URI
    # Then exchange the authorization respnse (which contains the auth code) to get the credentials
    flow.fetch_token(authorization_response=authorization_response)
    credentials = flow.credentials

    return credentials
Beispiel #2
0
def callback():
    """ Step 3: Retrieving an access token.

    The user has been redirected back from the provider to your registered
    callback URL. With this redirection comes an authorization code included
    in the redirect URL. We will use that to obtain an access token.
    """
    # print('Getting back from callvack :')
    state = session['oauth_state']
    google = Flow.from_client_secrets_file('client_secrets.json',
                                           scopes=scopes,
                                           redirect_uri=redirect_uri,
                                           state=state)
    token = google.fetch_token(authorization_response=request.url)

    client = bigquery.Client(project=project, credentials=google.credentials)

    query_job = client.query(query_string)

    rows = query_job.result()
    out = ""
    for row in rows:
        out = out + '<br/>' + str(row)

    return out
Beispiel #3
0
    def get():
        # Specify the state when creating the flow in the callback so that it can
        # verified in the authorization server response.
        result = MongoDB.instance().authorization.find_one({
            'service': 'calendar-service',
            'type': 'state'
        })
        state = result['state']

        flow = Flow.from_client_secrets_file('.secrets/credentials.json',
                                             SCOPES,
                                             state=state)
        flow.redirect_uri = request.args.get('redirect_uri')

        # Use the authorization server's response to fetch the OAuth 2.0 tokens.
        authorization_response = request.url
        flow.fetch_token(authorization_response=authorization_response)

        # Store credentials in mongo.
        credentials = flow.credentials
        MongoDB.instance().authorization.replace_one(
            {
                'service': 'calendar-service',
                'type': 'credentials'
            },
            credentials_to_dict(credentials),
            upsert=True,
        )

        return make_response({'message': 'Successfully authorized.'}, 200)
Beispiel #4
0
def ViewCourseWork(chat_id, course_id):

    course_id = ''
    creds = None
    pickleToken_path = "AddCourse/" + str(chat_id) + "_token.pickle"
    credentials_path = "AddCourse/credentials.json"

    if os.path.exists(pickleToken_path):
        with open(pickleToken_path, 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = Flow.from_client_secrets_file(credentials_path, SCOPES)
            creds = flow.run_local_server(port=users)

        with open(pickleToken_path, 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

    students_list = service.courses().courseWork().list(
        courseId=course_id).execute()
    return students_list
Beispiel #5
0
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.
  state = session['state']

  flow = Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE,
      scopes=None,        state=state,
      redirect_uri=url_for('oauth2callback', _external=True)
  )



  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = request.url
  flow.fetch_token(authorization_response=authorization_response)



  # Store credentials in the session.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  credentials = flow.credentials
  session['credentials'] = credentials_to_dict(credentials)


  

  return redirect('/')
Beispiel #6
0
def load_credentials():
    Path.mkdir(CONFIG_PATH, exist_ok=True)
    flow = Flow.from_client_secrets_file(
        CREDENTIALS_PATH, SCOPES,
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    token = open_file(TOKEN_PATH, formatter=json.loads)
    return create_credentials(token, flow)
Beispiel #7
0
    def credentialsCheck(self):

        print('credentialsCheck::starting')

        if not self.creds or not self.creds.valid:
            if self.creds and self.creds.expired \
                and self.creds.refresh_token:
                self.creds.refresh(Request())
            else:
                '''
                pathChecks is done here, this will only run at first launch
                after checking, we set the defaults values programmatically.
                '''
                self.pathChecks([self.config, self.download_path])
                self.createConfigBody()

                flow = Flow.from_client_secrets_file(
                    self.client_id,
                    header.SCOPES,
                    redirect_uri='urn:ietf:wg:oauth:2.0:oob')
                self.flow = flow

                (auth_url, _) = flow.authorization_url(prompt='consent')

                pyotherside.send('authUrl', str(auth_url))
Beispiel #8
0
def oauth2callback():
	flow = Flow.from_client_secrets_file(
		CLIENT_SECRET,
		scopes=SCOPES,
		redirect_uri=flask.url_for(
			'oauth2callback',
			_external=True
	))
	if 'code' not in flask.request.args:
		auth_url, state = flow.authorization_url(
			access_type="offline",
			include_granted_scopes='true'
		)
		flask.session['state'] = state
		return flask.redirect(auth_url)
	else:
		state = flask.session['state']
		flow.state = state

		auth_code = flask.request.args.get('code')
		flow.fetch_token(code=auth_code)
		credentials = flow.credentials

		flask.session['credentials'] = creds_to_dict(credentials)
		return flask.redirect(flask.url_for('index'))
Beispiel #9
0
def get_flow(
    redirect_uri: str,
    path_to_secrets: str,
    verification_string: str,
    state=None,
) -> 'Flow':
    ''' 
    Utility method to handle OAuth conversation with Google

    Params:
    -------
        redirect_uri: str
            Path to callback endpoint
        path_to_secrets: str
            Path to json file containing oauth secrets
        verification_string: str
            Random string to serve as an auth check on the callback

    '''

    flow = Flow.from_client_secrets_file(
        path_to_secrets,
        scopes=os.environ.get('SCOPES').split(','),
        state=state,
    )

    flow.redirect_uri = redirect_uri
    flow.code_verifier = verification_string
    return flow
Beispiel #10
0
def GetCourses(chat_id):

    creds = None
    pickleToken_path = "GetCourses/" + str(chat_id) + "_token.pickle"
    credentials_path = "GetCourses/credentials.json"

    if os.path.exists(pickleToken_path):
        with open(pickleToken_path, 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = Flow.from_client_secrets_file(credentials_path, SCOPES)
            creds = flow.run_local_server(port=users)

        with open(pickleToken_path, 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

    results = service.courses().list().execute()
    courses = results.get('courses', [])

    answer = []
    if not courses:
        answer.append('No courses found.')
    else:
        answer.append('Courses:')
        for course in courses:
            answer.append(course['name'])
    return answer
def get_credentials():
    """Generates new credentials for google api.

    TODO: google_auth has yet to implement storage, so that may have wait for
    another day.
    TODO: This also doesn't automatically open in your browser.

    """
    # We only need read permissions.
    scopes = [
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/spreadsheets.readonly'
    ]

    flow = Flow.from_client_secrets_file(
        'client_secret.json', scopes, redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    auth_url, _ = flow.authorization_url(prompt='consent')
    print('Go to')
    print(auth_url)
    print('and copy Auth Code')

    code = input('Enter auth code: ')
    print("Fetching Token.")
    flow.fetch_token(code=code)
    return flow.credentials
def s_complete(request):
    state = request.GET.get('state')
    # scope = ["https://www.googleapis.com/auth/userinfo.email.read", " https://www.googleapis.com/auth/userinfo.profile"]
    code = request.GET.get('code')
    prompt = request.GET.get('prompt')
    request.session['user'] = {}
    request.session['user']['state'] = state
    flow = Flow.from_client_secrets_file(BASE + '/accounts/client_secret.json',
                                         scopes=None,
                                         state=state)
    flow.redirect_uri = f'{settings.HOST}/complete/google-oauth2/'
    try:
        req_state = request.META['QUERY_STRING'] if "state" in request.META[
            'QUERY_STRING'] else request.scope['query_string']
    except:
        req_state = None
    print(req_state)

    print(state, code, prompt, sep="\n")
    authorization_response = request.get_raw_uri()
    if state in str(req_state):
        flow.fetch_token(authorization_response=authorization_response)
        credentials = flow.credentials
        service = build('people', 'v1', credentials=credentials)
        profile = service.people().get(
            resourceName='people/me', personFields='emailAddresses').execute()
        print(profile)
        user = AllProcedures.getUserWithEmail(
            profile['emailAddresses'][0]['value'])
        if user:
            return _login(request, user, "a", True)
        request.session['user']['email'] = profile['emailAddresses'][0][
            'value']
    return redirect("accounts:selectusertype")
Beispiel #13
0
def authorize():
    '''
    Create a flow instance to manage the OAuth2 Authorization Grant Flow steps

    .. :quickref: User; Create a flow instance to manage the OAuth2
    '''
    # Check if user is logged_in, then redirect to main page.
    if session.get('logged_in', None):
        flash('You are already logged in.', 'warning')
        return redirect(url_for('main.list_categories'))

    # Create the flow instance using the client secret file
    flow = Flow.from_client_secrets_file(app.config['CLIENT_SECRET_FILE'],
                                         scopes=app.config['SCOPES'])
    # Add the redirect_uri to the oauth2session
    flow.redirect_uri = url_for('.oauth2callback', _external=True)

    # Generate the Authorization URL. Step 1 in the Oauth2.0 Authorization Flow
    authorization_url, state = flow.authorization_url(
        # Enable offline access to prevent re-prompting the user for permission
        access_type='offline',
        # Enable incremental authorization.
        include_granted_scopes='true')

    # Store the state in the session to verify the callback.
    session['state'] = state

    # Redirect the user to Google OAuth page to obtain consent
    return redirect(authorization_url)
Beispiel #14
0
def doauth():
    print('in /doauth')

    client_config_str = os.getenv('GOOGLE_CLIENT_SECRETS', None)
    if client_config_str:
        client_config = json.loads(client_config_str)
        flow = Flow.from_client_config(client_config=client_config,
                                       scopes=SCOPES)
    else:
        # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
        flow = Flow.from_client_secrets_file(CLIENT_SECRET_FILE, scopes=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 = url_for('auth', _scheme='https', _external=True)
    if 'localhost' in flow.redirect_uri:
        flow.redirect_uri = url_for('auth', _scheme='http', _external=True)

    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)
Beispiel #15
0
def _get_user_authentication_credentials(client_secret_file,
                                         scopes,
                                         credential_directory=None,
                                         local=False):
    """Returns user credentials."""
    if credential_directory is None:
        credential_directory = os.getcwd()
    elif credential_directory == 'global':
        home_dir = os.path.expanduser('~')
        credential_directory = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_directory):
            os.makedirs(credential_directory)
    else:
        pass

    credentials_path = os.path.join(
        credential_directory,
        'sheets.googleapis.com-python.json')  # TODO Change hardcoded name?

    credentials = None
    if os.path.exists(credentials_path):
        # expect these to be valid. may expire at some point, but should be refreshed by google api client...
        credentials = Credentials.from_authorized_user_file(credentials_path,
                                                            scopes=scopes)

    if credentials:
        if credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
    else:
        if local:
            flow = InstalledAppFlow.from_client_secrets_file(
                client_secret_file, scopes)
            credentials = flow.run_local_server()
        else:
            flow = Flow.from_client_secrets_file(
                client_secret_file,
                scopes=scopes,
                redirect_uri='urn:ietf:wg:oauth:2.0:oob')
            auth_url, _ = flow.authorization_url(prompt='consent')

            print(
                'Please go to this URL and finish the authentication flow: {}'.
                format(auth_url))
            code = input('Enter the authorization code: ')
            flow.fetch_token(code=code)
            credentials = flow.credentials

    # Save the credentials for the next run
    credentials_as_dict = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'id_token': credentials.id_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret
    }
    with open(credentials_path, 'w') as file:
        file.write(json.dumps(credentials_as_dict))

    return credentials
Beispiel #16
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    try:
        # Save the credentials for the next run
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
            return creds
    except:
        print("Failed to load cached credentials")
    flow = Flow.from_client_secrets_file(CLIENT_SECRET_FILE, scopes=[SCOPE], redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    auth_url, _ = flow.authorization_url(prompt='consent')

    print('Please go to this URL: {}'.format(auth_url))

    # The user will get an authorization code. This code is used to get the
    # access token.
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
         pickle.dump(flow.credentials, token)
    return flow.credentials
Beispiel #17
0
def set_up_youtube_tokens():
    client_secrets_file = constants.YOUTUBE_CLIENT_SECRETS
    scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

    # Get credentials and create an API client
    flow = Flow.from_client_secrets_file(
        client_secrets_file,
        scopes,
        redirect_uri="urn:ietf:wg:oauth:2.0:oob"
    )

    # Get the authorization url and prompt the user to follow it
    auth_url, _ = flow.authorization_url(prompt="consent")
    print("Please go to this URL: {}".format(auth_url))
    code = input("Enter the authorization code: ")
    
    flow.fetch_token(code=code)
    credentials = flow.credentials

    youtube_tokens = {
        "access_token": credentials.token,
        "refresh_token": credentials.refresh_token,
        "token_uri": credentials.token_uri,
        "client_id": credentials.client_id,
        "client_secret": credentials.client_secret
    }

    with open(constants.YOUTUBE_SECRETS, "w") as secrets:
        json.dump(youtube_tokens, secrets)
Beispiel #18
0
def authGoogle(client_secret_file, scopes, redirect_uri):
    """
    Function that signs into google

    Parameters
    client_secret_file : String name of the json file containing api access information
    scopes : List of strings indicating the scope of the API service
    redirect_uri : String url where to redirect after authentication flow

    Returns the url for google sign in prompt and the current state to be stored in Flask
    session for authGoogleComplete.

    """
    # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
    flow = Flow.from_client_secrets_file(client_secret_file, scopes=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 = 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',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    return (authorization_url, state)
Beispiel #19
0
    def get():
        flow = Flow.from_client_secrets_file('.secrets/credentials.json',
                                             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 = request.args.get('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',
            # Enable incremental authorization. Recommended as a best practice.
            include_granted_scopes='true',
        )

        # Store the state so the callback can verify the auth server response.
        MongoDB.instance().authorization.replace_one(
            {
                'service': 'calendar-service',
                'type': 'state'
            },
            {
                'service': 'calendar-service',
                'type': 'state',
                'state': state
            },
            upsert=True,
        )

        return {'authorization_url': authorization_url}
def get_flow():
    """
    Create flow object.
    """
    return Flow.from_client_secrets_file(
        os.getenv('GOOGLE_SECRETS_FILE'),
        scopes='https://www.googleapis.com/auth/calendar.events',
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
Beispiel #21
0
def get_flow(state):
    # google認証フローを生成する
    params = {"scopes": SCOPES}
    if state is not None:
        params["state"] = state
    flow = Flow.from_client_secrets_file(CLIENT_SECRET_FILE, **params)
    flow.redirect_uri = url_for('auth.callback', _external=True)
    return flow
def authorize():
    print("authorize request")
    flow = Flow.from_client_secrets_file(oauth_secrets, scopes=SCOPES)
    flow.redirect_uri = flask.url_for("oauth_callback", _external=True)
    authorization_url, state = flow.authorization_url(
        access_type="offline", include_granted_scopes="true")
    flask.session["state"] = state
    print(f"redirecting to {authorization_url}")
    return flask.redirect(authorization_url)
Beispiel #23
0
 def prepare_login_url(self):
     self.flow = Flow.from_client_secrets_file(CLIENT_SECRET_FILE,
                                               scopes=SCOPES,
                                               redirect_uri=url_for(
                                                   'authenticate_user',
                                                   _external=True))
     return self.flow.authorization_url(access_type='offline',
                                        prompt='consent',
                                        include_granted_scopes='true')[0]
Beispiel #24
0
def authorize(request):
    flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=SCOPES)
    flow.redirect_uri = request.build_absolute_uri(reverse('ouath_callback'))

    authorization_url, state = flow.authorization_url(access_type='offline',\
      include_granted_scopes='true', approval_prompt='force')
    request.session['state'] = state
    authorization_url = authorization_url + '/'
    return redirect(authorization_url)
Beispiel #25
0
def authorize(request):
    # Flow
    flow = Flow.from_client_secrets_file(CLIENT_SECRET_FILE, scopes=[SCOPES])
    flow.redirect_uri = REDIRECT_URI
    authorization_url, state = flow.authorization_url(
        access_type='offline', prompt='consent', include_granted_scopes='true')
    SESSION['state'] = state
    print(list(request.GET.items()))
    return HttpResponseRedirect(authorization_url)
def gconnect():
    #verify integrity of the id token
    # state = hashlib.sha256(os.urandom(1024)).hexdigest()
    # #login_session holds my string value called "state"
    # login_session['state'] = state
    
    # if not request.headers.get('X-Requested-With'):
    #     abort(403)

    # if request.args.get('state') != login_session['state']:
    #     response = make_response(json.dumps('Invalid state parameter.'), 401)
    #     response.headers['Content-Type'] = 'application/json'
    # return response

    code = request.data
    #exchange the auth code here
    flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    flow.redirect_uri('http://localhost:8000/login')
    authorization_url, state = flow.authorization_url(
        access_type = 'offline',
        include_granted_scopes='true',
        prompt='select_account'
    )

    login_session['state'] = state
    return redirect(authorization_url)
    flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, STATE=state)
    flow.redirect_uri = url_for('http://localhost:8000', _external=True)

    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    credentials = flow.credentials
    login_session['credentials'] = {
        'token' : credentials.token,
        'refresh_token' : credentials.refresh_token,
        'token_uri' : credentials.token_uri,
        'client_id' : credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes' : credentials.scopes
    }

    auth = build('oauth2', 'v2', credentials=credentials)
    return redirect(url_for(auth))
Beispiel #27
0
def google_call(request, next_call):
    """
    :param request:
    :param next_call: str
        name of the url what will be called by google.
    """

    # # view names that require logged in user
    # if next_call in REQUIRE_LOGGED_IN_URL_NAMES:
    #     # view require logged in user
    #     if not request.user.is_authenticated:
    #         return redirect_to_login(request.path, login_url=reverse('login'))

    # if callback from google go to a view that require logged in user, and user is not looged in
    # redirect user
    if f'next_call:{not request.user.is_authenticated}' in next_call_isauthenticated_set:
        return redirect_to_login(request.path, login_url=reverse('login'))

    # Use the client_secret.json file to identify the application requesting
    # authorization. The client ID (from that file) and access scopes are required.
    flow = None
    try:
        flow = Flow.from_client_secrets_file(
            GOOGLE_CLIENT_FILE_PATH,
            SCOPES,
        )
    except ValueError as err:
        print(err)
        return redirect('google_error')
    # Indicate where the API server will redirect the user after the user completes
    # the authorization flow. The redirect URI is required. The value 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.
    try:
        # todo any better idea to make the url?
        # request.build_absolute_uri(reverse('view_name', args=(obj.pk, ))) TODO test if works
        flow.redirect_uri = '%s%s' % (request.build_absolute_uri('/')[:-1],
                                      reverse(next_call))
    except KeyError as err:
        print(err)
        return redirect('google_error')

    # Generate URL for request to Google's OAuth 2.0 server.
    # Use kwargs to set optional request parameters.
    # Enable incremental authorization. Recommended as a best practice.
    # include_granted_scopes = 'true',
    # login_hint=request.user.is_anonymous or request.user.email,
    # re-prompting the user for permission. Recommended for web server apps.
    # prompt='consent',
    # Enable offline access so that you can refresh an access token without
    # access_type = 'offline',

    authorization_url, state = flow.authorization_url(**GOOGLE_OPTIONS)

    return redirect(authorization_url)
Beispiel #28
0
 def get_url(self):
     self.flow = Flow.from_client_secrets_file(
         '../data/credentials.json',
         scopes=[
             'https://www.googleapis.com/auth/userinfo.email',
             'https://www.googleapis.com/auth/drive.file', 'openid'
         ],
         redirect_uri='urn:ietf:wg:oauth:2.0:oob')
     self.auth_url, _ = self.flow.authorization_url(prompt='consent')
     return self.auth_url
Beispiel #29
0
    def login_with_google(self , page):
        flow = Flow.from_client_secrets_file(self.file_path,**self.kwargs)

        authorization_url , state = flow.authorization_url(
            include_granted_scopes='true',prompt="select_account")

        session['state'] = state
        session['page'] = page

        return redirect(authorization_url)
Beispiel #30
0
    def google_callback(self):
        flow = Flow.from_client_secrets_file(self._path, scopes=SCOPES)
        flow.redirect_uri = url_for('login_blue.google_callback',
                                    _external=True)

        authorization_response = request.url
        flow.fetch_token(authorization_response=authorization_response)

        credentials = flow.credentials
        return self.__credentials_to_dict(credentials)
Beispiel #31
0
def _get_user_authentication_credentials(client_secret_file, scopes, credential_directory=None):
    """Returns user credentials."""
    if credential_directory is None:
        credential_directory = os.getcwd()
    elif credential_directory == 'global':
        home_dir = os.path.expanduser('~')
        credential_directory = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_directory):
            os.makedirs(credential_directory)
    else:
        pass

    credentials_path = os.path.join(credential_directory, 'sheets.googleapis.com-python.json')  # TODO Change hardcoded name?

    if os.path.exists(credentials_path):
        # expect these to be valid. may expire at some point, but should be refreshed by google api client...
        return Credentials.from_authorized_user_file(credentials_path, scopes=scopes)

    flow = Flow.from_client_secrets_file(client_secret_file, scopes=scopes,
                                         redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    auth_url, _ = flow.authorization_url(prompt='consent')

    print('Please go to this URL and finish the authentication flow: {}'.format(auth_url))
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)

    credentials = flow.credentials

    credentials_as_dict = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'id_token': credentials.id_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret
    }

    with open(credentials_path, 'w') as file:
        file.write(json.dumps(credentials_as_dict))

    return credentials